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

Outlook Calendar: Refresh a Delegated Access Token

See more Outlook Calendar Examples

Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.

Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.

The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each cache associated with its original app and account.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.

Microsoft documentation

Chilkat Delphi DLL Downloads

Delphi DLL
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/outlookCalendar.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/outlookCalendar.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/outlookCalendar.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 calendar token cache.');

CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(req);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkDateTime_Dispose(obtained);