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.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
JsonObject token = new JsonObject();
token.setStrict(true);
try {
token.loadFile("qa_data/tokens/oneDrive.json");
} catch (ChilkatException e) {
System.out.println("Read the private token cache or authorize again.");
return;
}
if ((token.jsonTypeOf("refresh_token") != 1) || (token.stringOfEquals("refresh_token", "", 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";
Http http = new Http();
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
http.setConnectTimeout(20);
http.setReadTimeout(30);
HttpRequest req = new HttpRequest();
req.setHttpVerb("POST");
req.setContentType("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.
HttpResponse resp = new HttpResponse();
JsonObject result = new JsonObject();
result.setStrict(true);
try {
http.httpReq(tokenUrl, req, resp);
success = true;
} catch (ChilkatException e) {
success = false;
}
// A false result can still include an HTTP error response.
if ((!success) && (resp.getStatusCode() == 0)) {
System.out.println("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
return;
}
if (resp.getStatusCode() != 200) {
System.out.println("Unexpected HTTP status: " + resp.getStatusCode());
System.out.println("Request ID: " + resp.getHeaderField("request-id"));
if (resp.getStatusCode() == 429) {
System.out.println("Retry-After: " + resp.getHeaderField("Retry-After"));
}
if (resp.getStatusCode() == 401) {
System.out.println("Refresh the Graph access token or authorize again.");
}
return;
}
try {
result.load(resp.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Expected a well-formed JSON response.");
return;
}
if ((result.jsonTypeOf("access_token") != 1) || (result.stringOfEquals("access_token", "", 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))) {
System.out.println("Expected a nonempty refresh_token in the JSON.");
return;
}
}
DateTime obtained = new DateTime();
try {
obtained.setFromCurrentSystemTime();
} catch (ChilkatException e) {
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.
try {
token.writeFile("qa_data/tokens/oneDrive.json.bak");
} catch (ChilkatException e) {
System.out.println("Could not back up the old cache; no replacement attempted.");
return;
}
try {
result.writeFile("qa_data/tokens/oneDrive.json");
} catch (ChilkatException e) {
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.");
}
}