Outlook Contacts: Refresh a Delegated Access Token
See more Outlook Contact Examples
After interactive authorization, refresh the Graph access token without reopening a browser. Use the same app client ID and authority as the contacts OAuth2 example. Omitting scope retains the original grant. This is delegated access, not application authentication; invalid_grant or an interaction requirement needs fresh interactive authorization.
The example validates the response, retains the previous refresh token when no replacement is returned, and saves a rotated token when present. HTTP or validation failures leave the old cache unchanged. A private backup protects against replacement-write failure; production applications should use protected atomic credential storage and serialize refreshes per account. Tokens are never printed.
Uses qa_data/tokens/outlookContacts.json. Refresh before the acquired time plus expires_in lifetime elapses. Keep the 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 contact data 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/outlookContacts.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/outlookContacts.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/outlookContacts.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 contacts token cache.');
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(req);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkDateTime_Dispose(obtained);