@@ -61,9 +61,14 @@ public OAuthHandler(OkHttpClient httpClient, OAuthConfig config) {
6161
6262
6363 private Request .Builder _getHeaders () {
64- return new Request .Builder ()
65- .header ("Content-Type" , "application/x-www-form-urlencoded" )
66- .header ("authorization" , "Bearer " + (tokens != null ? tokens .getAccessToken () : "" ));
64+ Request .Builder builder = new Request .Builder ()
65+ .header ("Content-Type" , "application/x-www-form-urlencoded" );
66+
67+ // Only add authorization header for non-token endpoints
68+ if (tokens != null && tokens .getAccessToken () != null ) {
69+ builder .header ("authorization" , "Bearer " + tokens .getAccessToken ());
70+ }
71+ return builder ;
6772 }
6873
6974 /**
@@ -194,8 +199,11 @@ public CompletableFuture<OAuthTokens> refreshAccessToken() {
194199 .add ("refresh_token" , tokens .getRefreshToken ())
195200 .add ("client_id" , config .getClientId ());
196201
197- if (!config .isPkceEnabled ()) {
202+ // Add client_secret if available, otherwise add code_verifier
203+ if (config .getClientSecret () != null && !config .getClientSecret ().trim ().isEmpty ()) {
198204 formBuilder .add ("client_secret" , config .getClientSecret ());
205+ } else if (this .codeVerifier != null ) {
206+ formBuilder .add ("code_verifier" , this .codeVerifier );
199207 }
200208
201209 Request request = _getHeaders ()
@@ -233,10 +241,13 @@ private OAuthTokens executeTokenRequest(Request request) throws IOException {
233241 String error = responseBody != null ? responseBody .string () : "Unknown error" ;
234242 System .err .println ("Error Response Body: " + error );
235243
236- // Parse error response if possible
244+ // Try to parse error as JSON for better error message
237245 try {
238- throw new RuntimeException ("Token request failed: " + error );
246+ com .contentstack .cms .models .Error errorObj = gson .fromJson (error , com .contentstack .cms .models .Error .class );
247+ throw new RuntimeException ("Token request failed: " +
248+ (errorObj != null ? errorObj .getErrorMessage () : error ));
239249 } catch (JsonParseException e ) {
250+ // If not JSON, use raw error string
240251 throw new RuntimeException ("Token request failed with status " +
241252 response .code () + ": " + error );
242253 }
@@ -364,4 +375,12 @@ public CompletableFuture<Void> revokeOauthAppAuthorization() {
364375 public String getOrganizationUID () { return tokens != null ? tokens .getOrganizationUid () : null ; }
365376 public String getUserUID () { return tokens != null ? tokens .getUserUid () : null ; }
366377 public Long getTokenExpiryTime () { return tokens != null ? tokens .getExpiresIn () : null ; }
378+
379+ /**
380+ * Checks if we have a valid access token
381+ * @return true if we have a non-expired access token
382+ */
383+ public boolean hasValidAccessToken () {
384+ return tokens != null && tokens .hasAccessToken () && !tokens .isExpired ();
385+ }
367386}
0 commit comments