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

Box: Get a Service Account Token with JWT

See more Box Examples

Use the encrypted private key in a Box application configuration file to sign a short-lived assertion and exchange it for an access token. Configure and authorize a JWT Server app first. The enterprise subject obtains the service-account token.

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.HttpCurl,
  Chilkat.PrivateKey,
  Chilkat.Prng,
  Chilkat.Jwt,
  Chilkat.JsonObject;

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

procedure RunDemo;
var
  success: Boolean;
  config: TJsonObject;
  key: TPrivateKey;
  header: TJsonObject;
  jwt: TJwt;
  prng: TPrng;
  nonce: string;
  claims: TJsonObject;
  assertion: string;
  curl: THttpCurl;

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;

  config := TJsonObject.Create;
  success := config.LoadFile('qa_data/tokens/box_jwt_config.json');
  if (success <> True) then
    begin
      WriteLn(config.LastErrorText);
      Exit;
    end;
  key := TPrivateKey.Create;
  success := key.LoadEncryptedPem(config.StringOf('boxAppSettings.appAuth.privateKey'),config.StringOf('boxAppSettings.appAuth.passphrase'));
  if (success <> True) then
    begin
      WriteLn(key.LastErrorText);
      Exit;
    end;
  header := TJsonObject.Create;
  header.UpdateString('alg','RS256');
  header.UpdateString('typ','JWT');
  header.UpdateString('kid',config.StringOf('boxAppSettings.appAuth.publicKeyID'));
  jwt := TJwt.Create;
  prng := TPrng.Create;
  nonce := prng.GenRandom(32,'hex');
  if (prng.LastMethodSuccess <> True) then
    begin
      WriteLn(prng.LastErrorText);
      Exit;
    end;
  claims := TJsonObject.Create;
  claims.UpdateString('iss',config.StringOf('boxAppSettings.clientID'));
  claims.UpdateString('sub',config.StringOf('enterpriseID'));
  claims.UpdateString('box_sub_type','enterprise');
  claims.UpdateString('aud','https://api.box.com/oauth2/token');
  claims.UpdateString('jti',nonce);
  claims.UpdateInt('exp',jwt.GenNumericDate(45));
  assertion := jwt.CreateJwtPk(header.Emit(),claims.Emit(),key);
  if (jwt.LastMethodSuccess <> True) then
    begin
      WriteLn(jwt.LastErrorText);
      Exit;
    end;
  curl := THttpCurl.Create;
  curl.SetVar('client_id',config.StringOf('boxAppSettings.clientID'));
  curl.SetVar('client_secret',config.StringOf('boxAppSettings.clientSecret'));
  curl.SetVar('assertion',assertion);
  curl.ClearTargetOutput('*');
  curl.ClearVar('access_token');
  curl.AddTargetOutput('access_token','access_token');
  success := curl.DoYourThing('curl -X POST "https://api.box.com/oauth2/token" --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" --data-urlencode "client_id={{client_id}}" --data-urlencode "client_secret={{client_secret}}" --data-urlencode "assertion={{assertion}}"');
  if ((success <> True) or (curl.StatusCode <> 200)) then
    begin
      WriteLn('Box request failed. HTTP status: ' + curl.StatusCode);
      WriteLn('Failure reason: ' + curl.FailReason);
      Exit;
    end;
  if (curl.VarDefined('!') <> True) then
    begin
      WriteLn('Expected response fields are missing.');
      Exit;
    end;
  //  Reuse the token in this HttpCurl instance. JWT tokens are renewed by making
  //  a new assertion/token request, not by using a refresh token.
  WriteLn('JWT access token obtained.');


  config.Free;
  key.Free;
  header.Free;
  jwt.Free;
  prng.Free;
  claims.Free;
  curl.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.