Sample code for 30+ languages & platforms
Delphi DLL

Refresh Access Token on 401 Unauthorized and Retry (Service Account)

See more Google Cloud Storage Examples

Demonstrates how to handle an expired access token error, refresh the token, and retry the request. (In this case, the request is to download an object from Google Cloud Storage.)

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, AuthGoogle, Socket, FileAccess, BinData, StringBuilder, Http;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
sbToken: HCkStringBuilder;
http: HCkHttp;
url: PWideChar;
fileData: HCkBinData;
responseCode: Integer;
fac: HCkFileAccess;
jsonKey: PWideChar;
gAuth: HCkAuthGoogle;
tlsSock: HCkSocket;
sbErrorResponse: HCkStringBuilder;

begin
success := False;

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

// This example uses a previously obtained access token having permission for the 
// scope "https://www.googleapis.com/auth/cloud-platform"

// In this example, Get Google Cloud Storage OAuth2 Access Token, 
// the service account access token was saved to a text file.  This example fetches the access token from the file..
sbToken := CkStringBuilder_Create();
success := CkStringBuilder_LoadFile(sbToken,'qa_data/tokens/googleCloudStorageAccessToken.txt','utf-8');
if (success = False) then
  begin
    Memo1.Lines.Add('Failed to load access token.');
    Exit;
  end;

http := CkHttp_Create();

CkHttp_putAuthToken(http,CkStringBuilder__getAsString(sbToken));

// Construct a URL to download an object named "starfish.jpg" from the "chilkat-ocean" bucket.
CkHttp_SetUrlVar(http,'bucket_name','chilkat-ocean');
CkHttp_SetUrlVar(http,'object_name','starfish.jpg');
url := 'https://www.googleapis.com/storage/v1/b/{$bucket_name}/o/{$object_name}?alt=media';

// If there is an error response, then we didn't actually download the file data,
// but instead we downloaded an error response..
fileData := CkBinData_Create();
success := CkHttp_DownloadBd(http,url,fileData);
responseCode := CkHttp_getLastStatus(http);
if ((success = False) and (responseCode <> 401)) then
  begin
    Memo1.Lines.Add(CkHttp__lastErrorText(http));
    Exit;
  end;

if (responseCode = 401) then
  begin
    Memo1.Lines.Add('Received 401 Unauthorized response. Attempting to refresh the access token...');

    // May be that the access token expired.
    // Load our JSON key and request a new access token, then retry the original request.
    fac := CkFileAccess_Create();
    jsonKey := CkFileAccess__readEntireTextFile(fac,'qa_data/googleApi/ChilkatCloud-13a07a2e8b3f.json','utf-8');
    if (CkFileAccess_getLastMethodSuccess(fac) <> True) then
      begin
        Memo1.Lines.Add(CkFileAccess__lastErrorText(fac));
        Exit;
      end;

    gAuth := CkAuthGoogle_Create();
    CkAuthGoogle_putJsonKey(gAuth,jsonKey);
    CkAuthGoogle_putScope(gAuth,'https://www.googleapis.com/auth/cloud-platform');
    CkAuthGoogle_putExpireNumSeconds(gAuth,3600);
    CkAuthGoogle_putSubEmailAddress(gAuth,'');

    tlsSock := CkSocket_Create();
    success := CkSocket_Connect(tlsSock,'www.googleapis.com',443,True,5000);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkSocket__lastErrorText(tlsSock));
        Exit;
      end;

    success := CkAuthGoogle_ObtainAccessToken(gAuth,tlsSock);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkAuthGoogle__lastErrorText(gAuth));
        Exit;
      end;

    CkFileAccess_WriteEntireTextFile(fac,'qa_data/tokens/googleCloudStorageAccessToken.txt',CkAuthGoogle__accessToken(gAuth),'utf-8',False);

    // Retry the original request.
    CkHttp_putAuthToken(http,CkAuthGoogle__accessToken(gAuth));
    success := CkHttp_DownloadBd(http,url,fileData);
    if (success = False) then
      begin
        Memo1.Lines.Add(CkHttp__lastErrorText(http));
        Exit;
      end;

  end;

if (responseCode <> 200) then
  begin
    // Get the error response
    sbErrorResponse := CkStringBuilder_Create();
    CkStringBuilder_AppendBd(sbErrorResponse,fileData,'utf-8',0,0);
    Memo1.Lines.Add('Error response code = ' + IntToStr(responseCode));
    Memo1.Lines.Add('Error:');
    Memo1.Lines.Add(CkStringBuilder__getAsString(sbErrorResponse));
    Exit;
  end;

Memo1.Lines.Add('Success.');

// Save the downloaded data to a file.
success := CkBinData_WriteFile(fileData,'qa_output/starfish.jpg');

CkStringBuilder_Dispose(sbToken);
CkHttp_Dispose(http);
CkBinData_Dispose(fileData);
    CkFileAccess_Dispose(fac);
    CkAuthGoogle_Dispose(gAuth);
    CkSocket_Dispose(tlsSock);
    CkStringBuilder_Dispose(sbErrorResponse);

end;