Sample code for 30+ languages & platforms
CkJava Requires Chilkat v11.6.0+

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObject token = new CkJsonObject();
    token.put_Strict(true);
    success = token.LoadFile("qa_data/tokens/oneDrive.json");
    if (success != true) {
        System.out.println("Read the private token cache or authorize again.");
        return;
        }

    if ((token.JsonTypeOf("refresh_token") != 1) || (token.StringOfEquals("refresh_token","",true) == true)) {
        System.out.println("Expected a nonempty refresh_token in the JSON.");
        return;
        }

    String clientId = "YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    String tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(30);
    CkHttpRequest req = new CkHttpRequest();
    req.put_HttpVerb("POST");
    req.put_ContentType("application/x-www-form-urlencoded");
    req.AddParam("client_id",clientId);
    req.AddParam("grant_type","refresh_token");
    req.AddParam("refresh_token",token.stringOf("refresh_token"));
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    CkHttpResponse resp = new CkHttpResponse();
    CkJsonObject result = new CkJsonObject();
    result.put_Strict(true);
    success = http.HttpReq(tokenUrl,req,resp);
    //  A false result can still include an HTTP error response.
    if ((success != true) && (resp.get_StatusCode() == 0)) {
        System.out.println("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
        return;
        }

    if (resp.get_StatusCode() != 200) {
        System.out.println("Unexpected HTTP status: " + resp.get_StatusCode());
        System.out.println("Request ID: " + resp.getHeaderField("request-id"));
        if (resp.get_StatusCode() == 429) {
            System.out.println("Retry-After: " + resp.getHeaderField("Retry-After"));
            }

        if (resp.get_StatusCode() == 401) {
            System.out.println("Refresh the Graph access token or authorize again.");
            }

        return;
        }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Expected a well-formed JSON response.");
        return;
        }

    if ((result.JsonTypeOf("access_token") != 1) || (result.StringOfEquals("access_token","",true) == true)) {
        System.out.println("Expected a nonempty access_token in the JSON.");
        return;
        }

    if ((result.JsonTypeOf("expires_in") != 2) || (result.IntOf("expires_in") <= 0)) {
        System.out.println("Missing token lifetime; old cache unchanged.");
        return;
        }

    if (result.JsonTypeOf("refresh_token") == -1) {
        result.UpdateString("refresh_token",token.stringOf("refresh_token"));
        }
    else {
        if ((result.JsonTypeOf("refresh_token") != 1) || (result.StringOfEquals("refresh_token","",true) == true)) {
            System.out.println("Expected a nonempty refresh_token in the JSON.");
            return;
            }

        }

    CkDateTime obtained = new CkDateTime();
    success = obtained.SetFromCurrentSystemTime();
    if (success != true) {
        System.out.println("Could not timestamp the refreshed token.");
        return;
        }

    result.UpdateString("obtained_at",obtained.getAsTimestamp(false));
    //  Keep a valid previous cache for recovery if the replacement write fails.
    success = token.WriteFile("qa_data/tokens/oneDrive.json.bak");
    if (success != true) {
        System.out.println("Could not back up the old cache; no replacement attempted.");
        return;
        }

    success = result.WriteFile("qa_data/tokens/oneDrive.json");
    if (success != true) {
        System.out.println("Could not save the new token; recover the previous cache from the private .bak file.");
        return;
        }

    System.out.println("Refreshed the OneDrive token cache.");
  }
}