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 Delphi DLL Downloads
var
success: Boolean;
token: HCkJsonObject;
clientId: PWideChar;
tokenUrl: PWideChar;
http: HCkHttp;
req: HCkHttpRequest;
resp: HCkHttpResponse;
result: HCkJsonObject;
obtained: HCkDateTime;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/oneDrive.json');
if (success <> True) then
begin
Memo1.Lines.Add('Read the private token cache or authorize again.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(token,'refresh_token','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty refresh_token in the JSON.');
Exit;
end;
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 := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,30);
req := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(req,'POST');
CkHttpRequest_putContentType(req,'application/x-www-form-urlencoded');
CkHttpRequest_AddParam(req,'client_id',clientId);
CkHttpRequest_AddParam(req,'grant_type','refresh_token');
CkHttpRequest_AddParam(req,'refresh_token',CkJsonObject__stringOf(token,'refresh_token'));
// Omitting scope retains the original grant instead of requesting additional permissions.
resp := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
success := CkHttp_HttpReq(http,tokenUrl,req,resp);
// A false result can still include an HTTP error response.
if ((success <> True) and (CkHttpResponse_getStatusCode(resp) = 0)) then
begin
Memo1.Lines.Add('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
Exit;
end;
if (CkHttpResponse_getStatusCode(resp) <> 200) then
begin
Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(resp,'request-id'));
if (CkHttpResponse_getStatusCode(resp) = 429) then
begin
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(resp,'Retry-After'));
end;
if (CkHttpResponse_getStatusCode(resp) = 401) then
begin
Memo1.Lines.Add('Refresh the Graph access token or authorize again.');
end;
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(result,'access_token') <> 1) or (CkJsonObject_StringOfEquals(result,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty access_token in the JSON.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(result,'expires_in') <> 2) or (CkJsonObject_IntOf(result,'expires_in') <= 0)) then
begin
Memo1.Lines.Add('Missing token lifetime; old cache unchanged.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'refresh_token') = -1) then
begin
CkJsonObject_UpdateString(result,'refresh_token',CkJsonObject__stringOf(token,'refresh_token'));
end
else
begin
if ((CkJsonObject_JsonTypeOf(result,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(result,'refresh_token','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty refresh_token in the JSON.');
Exit;
end;
end;
obtained := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(obtained);
if (success <> True) then
begin
Memo1.Lines.Add('Could not timestamp the refreshed token.');
Exit;
end;
CkJsonObject_UpdateString(result,'obtained_at',CkDateTime__getAsTimestamp(obtained,False));
// Keep a valid previous cache for recovery if the replacement write fails.
success := CkJsonObject_WriteFile(token,'qa_data/tokens/oneDrive.json.bak');
if (success <> True) then
begin
Memo1.Lines.Add('Could not back up the old cache; no replacement attempted.');
Exit;
end;
success := CkJsonObject_WriteFile(result,'qa_data/tokens/oneDrive.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not save the new token; recover the previous cache from the private .bak file.');
Exit;
end;
Memo1.Lines.Add('Refreshed the OneDrive token cache.');
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(req);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkDateTime_Dispose(obtained);