Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Configure OAuth 2.0 Authentication for REST

See more REST Examples

Demonstrates Rest.SetAuthOAuth2, which associates an OAuth2 provider containing a valid access token so Chilkat adds the bearer token to the Authorization header.

Background. OAuth 2.0 bearer-token authentication attaches the access token to each request. The token is typically obtained separately through an OAuth 2.0 authorization flow before being assigned to the provider.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
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.Rest,
  Chilkat.OAuth2;

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

procedure RunDemo;
var
  success: Boolean;
  rest: TRest;
  bTls: Boolean;
  bAutoReconnect: Boolean;
  oauth2: TOAuth2;
  responseText: string;

begin
  success := False;

  rest := TRest.Create;
  bTls := True;
  bAutoReconnect := True;
  success := rest.Connect('example.com',443,bTls,bAutoReconnect);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;

  //  Configure OAuth 2.0 bearer-token authentication.  The provider must contain a valid access token.
  oauth2 := TOAuth2.Create;
  //  Normally you would not hard-code secrets in source.  You should instead obtain them from an
  //  interactive prompt, environment variable, or a secrets vault.
  oauth2.AccessToken := 'OAUTH2_ACCESS_TOKEN';

  //  Associate the provider so Chilkat adds the bearer token to the Authorization header.
  success := rest.SetAuthOAuth2(oauth2);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;

  responseText := rest.FullRequestNoBody('GET','/api/resource');
  if (rest.LastMethodSuccess = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  WriteLn(responseText);


  rest.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.