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 PHP Downloads
<?php
use Chilkat2\DateTime;
use Chilkat2\Http;
use Chilkat2\HttpRequest;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = false;
$token = new JsonObject();
$token->Strict = true;
try {
$token->LoadFile('qa_data/tokens/oneDrive.json');
} catch (\Chilkat2\Exception $e) {
echo "Read the private token cache or authorize again.\n";
exit;
}
if (($token->JsonTypeOf('refresh_token') != 1) || ($token->StringOfEquals('refresh_token', '', true))) {
echo "Expected a nonempty refresh_token in the JSON.\n";
exit;
}
$clientId = 'YOUR_APPLICATION_CLIENT_ID';
// Use the same app and authority as the original authorization.
$tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$http = new Http();
$http->RequireSslCertVerify = true;
$http->FollowRedirects = false;
$http->ConnectTimeout = 20;
$http->ReadTimeout = 30;
$req = new HttpRequest();
$req->HttpVerb = 'POST';
$req->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.
$resp = new HttpResponse();
$result = new JsonObject();
$result->Strict = true;
try {
$http->HttpReq($tokenUrl, $req, $resp);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
// A false result can still include an HTTP error response.
if ((!$success) && ($resp->StatusCode == 0)) {
echo "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.\n";
exit;
}
if ($resp->StatusCode != 200) {
echo 'Unexpected HTTP status: ', $resp->StatusCode, "\n";
echo 'Request ID: ', $resp->GetHeaderField('request-id'), "\n";
if ($resp->StatusCode == 429) {
echo 'Retry-After: ', $resp->GetHeaderField('Retry-After'), "\n";
}
if ($resp->StatusCode == 401) {
echo "Refresh the Graph access token or authorize again.\n";
}
exit;
}
try {
$result->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Expected a well-formed JSON response.\n";
exit;
}
if (($result->JsonTypeOf('access_token') != 1) || ($result->StringOfEquals('access_token', '', true))) {
echo "Expected a nonempty access_token in the JSON.\n";
exit;
}
if (($result->JsonTypeOf('expires_in') != 2) || ($result->IntOf('expires_in') <= 0)) {
echo "Missing token lifetime; old cache unchanged.\n";
exit;
}
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))) {
echo "Expected a nonempty refresh_token in the JSON.\n";
exit;
}
}
$obtained = new DateTime();
try {
$obtained->SetFromCurrentSystemTime();
} catch (\Chilkat2\Exception $e) {
echo "Could not timestamp the refreshed token.\n";
exit;
}
$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 (\Chilkat2\Exception $e) {
echo "Could not back up the old cache; no replacement attempted.\n";
exit;
}
try {
$result->WriteFile('qa_data/tokens/oneDrive.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not save the new token; recover the previous cache from the private .bak file.\n";
exit;
}
echo "Refreshed the OneDrive token cache.\n";