Sample code for 30+ languages & platforms
Android™

Refresh OAuth2 Access Token with Optional Params

See more OAuth2 Examples

Demonstrates how to refresh an OAuth2 access token with optional query params included in the HTTP request.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    // Here is a sampling of possible optional parameters that might
    // be used by some OAuth2 providers.

    // Optional Parameters
    // 
    //     "scope":
    //         Specifies the scope of the access request. If omitted, the authorization
    //         server may issue a token with the same scope as the original token.
    //         Example: "scope=read write"
    // 
    //     "redirect_uri":
    //         The redirect URI used in the original authorization request. Some
    //         servers may require this for validation.
    //         Example: "redirect_uri=https://example.com/callback"
    // 
    //     "resource":
    //         Indicates the target resource or audience for the token. This is used in
    //         some implementations (e.g., Microsoft Identity Platform).
    //         Example: "resource=https://api.example.com"
    // 
    //     "audience":
    //         Similar to "resource", this specifies the intended audience for the
    //         token (used in some OAuth2 implementations like Auth0).
    //         Example: "audience=https://api.example.com"
    // 
    //     "client_assertion" and "client_assertion_type":
    //         Used for client authentication using a signed JWT instead of a client
    //         secret.
    //         Example:client_assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...        
    //         client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
    // 
    //     "token_type_hint":
    //         Provides a hint to the authorization server about the type of token
    //         being refreshed. This is rarely used but can be helpful in some cases.
    //         Example: "token_type_hint=refresh_token"
    // 
    //     "assertion":
    //         Used in some flows (e.g., SAML bearer assertion flow) to provide an
    //         assertion for token issuance.
    //         Example: "assertion=PHNhbWxwOl..."
    // 
    //     "requested_token_use":
    //         Specifies how the token will be used (e.g., "on_behalf_of" in the
    //         On-Behalf-Of flow used by Microsoft Identity Platform).
    //         Example: "requested_token_use=on_behalf_of"
    // 

    // --------------------------------------------------------------------------------
    // This example wll refresh the access token and includes the "audience"
    // optional query parameter.
    // 
    // 

    // Get the access token to be refreshed.
    CkJsonObject jsonToken = new CkJsonObject();
    success = jsonToken.LoadFile("qa_data/tokens/myAccessToken.json");
    if (success != true) {
        Log.i(TAG, "Failed to load hmrc.json");
        return;
        }

    CkOAuth2 oauth2 = new CkOAuth2();

    oauth2.put_TokenEndpoint("https://api.example.com/oauth/token");

    // Replace these with actual values.
    oauth2.put_ClientId("CLIENT_ID");
    oauth2.put_ClientSecret("CLIENT_SECRET");

    // Add the optional refresh query param.
    // Call AddRefreshQueryParam multiple times to add additional params.
    oauth2.AddRefreshQueryParam("audience","https://api.example.com");

    // Provide the existing refresh token from the JSON.
    oauth2.put_RefreshToken(jsonToken.stringOf("refresh_token"));

    // Send the HTTP POST to refresh the access token..
    success = oauth2.RefreshAccessToken();
    if (success != true) {
        Log.i(TAG, oauth2.lastErrorText());
        return;
        }

    // Load the access token response into the json object 
    jsonToken.Load(oauth2.accessTokenResponse());

    // Save the new JSON access token response to a file.
    // The access + refresh tokens contained in this JSON will be needed for the next refresh.
    CkStringBuilder sbJson = new CkStringBuilder();
    jsonToken.put_EmitCompact(false);
    jsonToken.EmitSb(sbJson);
    sbJson.WriteFile("qa_data/tokens/myAccessToken.json","utf-8",false);

    Log.i(TAG, "OAuth2 access token refreshed!");
    Log.i(TAG, "New Access Token = " + oauth2.accessToken());

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}