Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.5.0+

Box: Refresh and Save Rotated OAuth Tokens

See more Box Examples

Refresh the user token saved by the authorization example. Box refresh tokens are single-use and expire after 60 days. Serialize refreshes for a token pair and save the replacement immediately; do not run concurrent refresh jobs.

See the Box API guide for setup and the complete workflow.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.JsonObject,
  Chilkat.OAuth2;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  tokens: TJsonObject;
  oauth2: TOAuth2;

begin
  success := False;

  //  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
  //  See Global Unlock Sample.
  //  Guide: Box API Guide.

  success := False;

  tokens := TJsonObject.Create;
  success := tokens.LoadFile('qa_data/tokens/box_oauth.json');
  if (success <> True) then
    begin
      WriteLn(tokens.LastErrorText);
      Exit;
    end;
  oauth2 := TOAuth2.Create;
  oauth2.TokenEndpoint := 'https://api.box.com/oauth2/token';
  oauth2.ClientId := 'BOX_CLIENT_ID';
  oauth2.ClientSecret := 'BOX_CLIENT_SECRET';
  oauth2.RefreshToken := tokens.StringOf('refresh_token');
  success := oauth2.RefreshAccessToken();
  if (success <> True) then
    begin
      WriteLn(oauth2.LastErrorText);
      Exit;
    end;
  success := tokens.Load(oauth2.AccessTokenResponse);
  if (success <> True) then
    begin
      WriteLn(tokens.LastErrorText);
      Exit;
    end;
  //  The previous refresh token is now invalid. Preserve this response even if
  //  your normal token-store write fails. Do not retry with the old refresh token.
  success := tokens.WriteFile('qa_data/tokens/box_oauth.json');
  if (success <> True) then
    begin
      WriteLn(tokens.LastErrorText);
      Exit;
    end;
  WriteLn('New access and refresh tokens saved. Do not log their values.');


  tokens.Free;
  oauth2.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.