Sample code for 30+ languages & platforms
Delphi DLL

Automatically Refresh Token for 401 Unauthorized

See more Google Calendar Examples

Demonstrates how to automatically refresh an access token (without user interaction) when the token expires and a 401 Unauthorized response is received.

Chilkat Delphi DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Http, OAuth2, StringBuilder, JsonObject;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
tokenFilePath: PWideChar;
jsonToken: HCkJsonObject;
http: HCkHttp;
jsonResponse: PWideChar;
oauth2: HCkOAuth2;
sbJson: HCkStringBuilder;

begin
success := False;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

tokenFilePath := 'qa_data/tokens/googleCalendar.json';

// Get our current access token.
jsonToken := CkJsonObject_Create();
success := CkJsonObject_LoadFile(jsonToken,tokenFilePath);
if (CkJsonObject_HasMember(jsonToken,'access_token') = False) then
  begin
    Memo1.Lines.Add('No access token found.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putAuthToken(http,CkJsonObject__stringOf(jsonToken,'access_token'));

jsonResponse := CkHttp__quickGetStr(http,'https://www.googleapis.com/calendar/v3/users/me/calendarList');
if (CkHttp_getLastMethodSuccess(http) <> True) then
  begin

    if (CkHttp_getLastStatus(http) <> 401) then
      begin
        Memo1.Lines.Add(CkHttp__lastErrorText(http));
        Memo1.Lines.Add('----');
        Memo1.Lines.Add(CkHttp__lastResponseBody(http));
        Exit;
      end;

    // The access token must've expired. 
    // Refresh the access token and then retry the request.
    oauth2 := CkOAuth2_Create();

    CkOAuth2_putTokenEndpoint(oauth2,'https://www.googleapis.com/oauth2/v4/token');

    // Replace these with actual values.
    CkOAuth2_putClientId(oauth2,'GOOGLE-CLIENT-ID');
    CkOAuth2_putClientSecret(oauth2,'GOOGLE-CLIENT-SECRET');

    // Get the "refresh_token"
    CkOAuth2_putRefreshToken(oauth2,CkJsonObject__stringOf(jsonToken,'refresh_token'));

    // Send the HTTP POST to refresh the access token..
    success := CkOAuth2_RefreshAccessToken(oauth2);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkOAuth2__lastErrorText(oauth2));
        Exit;
      end;

    // The response contains a new access token, but we must keep
    // our existing refresh token for when we need to refresh again in the future.
    CkJsonObject_UpdateString(jsonToken,'access_token',CkOAuth2__accessToken(oauth2));

    // Save the new JSON access token response to a file.
    sbJson := CkStringBuilder_Create();
    CkJsonObject_putEmitCompact(jsonToken,False);
    CkJsonObject_EmitSb(jsonToken,sbJson);
    CkStringBuilder_WriteFile(sbJson,tokenFilePath,'utf-8',False);

    Memo1.Lines.Add('OAuth2 authorization granted!');
    Memo1.Lines.Add('New Access Token = ' + CkOAuth2__accessToken(oauth2));

    // re-try the original request.
    CkHttp_putAuthToken(http,CkOAuth2__accessToken(oauth2));
    jsonResponse := CkHttp__quickGetStr(http,'https://www.googleapis.com/calendar/v3/users/me/calendarList');
    if (CkHttp_getLastMethodSuccess(http) <> True) then
      begin
        Memo1.Lines.Add(CkHttp__lastErrorText(http));
        Exit;
      end;
  end;

Memo1.Lines.Add(jsonResponse);
Memo1.Lines.Add('-----------------------------');

CkJsonObject_Dispose(jsonToken);
CkHttp_Dispose(http);
    CkOAuth2_Dispose(oauth2);
    CkStringBuilder_Dispose(sbJson);

end;