Sample code for 30+ languages & platforms
Delphi ActiveX 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 Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
token: TChilkatJsonObject;
clientId: WideString;
tokenUrl: WideString;
http: TChilkatHttp;
req: TChilkatHttpRequest;
resp: TChilkatHttpResponse;
result: TChilkatJsonObject;
obtained: TCkDateTime;

begin
success := 0;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := 0;
token := TChilkatJsonObject.Create(Self);
token.Strict := 1;
success := token.LoadFile('qa_data/tokens/oneDrive.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Read the private token cache or authorize again.');
    Exit;
  end;
if ((token.JsonTypeOf('refresh_token') <> 1) or (token.StringOfEquals('refresh_token','',1) = 1)) 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 := TChilkatHttp.Create(Self);
http.RequireSslCertVerify := 1;
http.FollowRedirects := 0;
http.ConnectTimeout := 20;
http.ReadTimeout := 30;
req := TChilkatHttpRequest.Create(Self);
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 := TChilkatHttpResponse.Create(Self);
result := TChilkatJsonObject.Create(Self);
result.Strict := 1;
success := http.HttpReq(tokenUrl,req.ControlInterface,resp.ControlInterface);
//  A false result can still include an HTTP error response.
if ((success <> 1) and (resp.StatusCode = 0)) then
  begin
    Memo1.Lines.Add('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
    Exit;
  end;
if (resp.StatusCode <> 200) then
  begin
    Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(resp.StatusCode));
    Memo1.Lines.Add('Request ID: ' + resp.GetHeaderField('request-id'));
    if (resp.StatusCode = 429) then
      begin
        Memo1.Lines.Add('Retry-After: ' + resp.GetHeaderField('Retry-After'));
      end;
    if (resp.StatusCode = 401) then
      begin
        Memo1.Lines.Add('Refresh the Graph access token or authorize again.');
      end;
    Exit;
  end;
success := result.Load(resp.BodyStr);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Expected a well-formed JSON response.');
    Exit;
  end;
if ((result.JsonTypeOf('access_token') <> 1) or (result.StringOfEquals('access_token','',1) = 1)) then
  begin
    Memo1.Lines.Add('Expected a nonempty access_token in the JSON.');
    Exit;
  end;
if ((result.JsonTypeOf('expires_in') <> 2) or (result.IntOf('expires_in') <= 0)) then
  begin
    Memo1.Lines.Add('Missing token lifetime; old cache unchanged.');
    Exit;
  end;
if (result.JsonTypeOf('refresh_token') = -1) then
  begin
    result.UpdateString('refresh_token',token.StringOf('refresh_token'));
  end
else
  begin
    if ((result.JsonTypeOf('refresh_token') <> 1) or (result.StringOfEquals('refresh_token','',1) = 1)) then
      begin
        Memo1.Lines.Add('Expected a nonempty refresh_token in the JSON.');
        Exit;
      end;
  end;
obtained := TCkDateTime.Create(Self);
success := obtained.SetFromCurrentSystemTime();
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not timestamp the refreshed token.');
    Exit;
  end;
result.UpdateString('obtained_at',obtained.GetAsTimestamp(0));
//  Keep a valid previous cache for recovery if the replacement write fails.
success := token.WriteFile('qa_data/tokens/oneDrive.json.bak');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not back up the old cache; no replacement attempted.');
    Exit;
  end;
success := result.WriteFile('qa_data/tokens/oneDrive.json');
if (success <> 1) 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.');