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

Jira Cloud: Refresh an OAuth2 Access Token

See more Jira Examples

Refresh a previously authorized Atlassian OAuth2 token without opening a browser. Run initial authorization first. Atlassian rotates refresh tokens: save the newly returned refresh token together with the access token before another refresh. Serialize refreshes for the same grant so concurrent processes do not overwrite each other's tokens.

The example writes a recovery file before updating the existing token cache. Keep both files in a private working directory. If writing the main cache fails, recover from jira-token.new.json. A production token store should provide an atomic replacement or transaction. An HTTP refresh failure leaves the old cache untouched. If authorization is revoked or the refresh token expires, obtain user consent again; do not repeatedly retry an invalid grant. The confidential client secret belongs in private application configuration or a backend, not a publicly distributed executable.

Targets Jira Cloud. Jira Data Center has a separate REST API and may require different paths, authentication, or payloads.

Atlassian REST API documentation

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.Http,
  Chilkat.FileAccess,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

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

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  request: TJsonObject;
  http: THttp;
  resp: THttpResponse;
  reply: TJsonObject;
  files: TFileAccess;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.

  token := TJsonObject.Create;
  success := token.LoadFile('jira-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not read the private token file.');
      Exit;
    end;
  if ((token.JsonTypeOf('refresh_token') <> 1) or (token.StringOfEquals('refresh_token','',True) = True)) then
    begin
      WriteLn('Missing value: refresh_token');
      Exit;
    end;
  request := TJsonObject.Create;
  request.UpdateString('grant_type','refresh_token');
  request.UpdateString('client_id','YOUR_CLIENT_ID');
  request.UpdateString('client_secret','YOUR_CLIENT_SECRET');
  request.UpdateString('refresh_token',token.StringOf('refresh_token'));
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  resp := THttpResponse.Create;
  reply := TJsonObject.Create;
  success := http.HttpJson('POST','https://auth.atlassian.com/oauth/token',request,'application/json',resp);
  if (resp.StatusCode = 0) then
    begin
      WriteLn('No HTTP response was received. Check connectivity and TLS settings.');
      Exit;
    end;
  if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
    begin
      WriteLn('Request failed. HTTP ' + resp.StatusCode);
      if (resp.StatusCode = 429) then
        begin
          WriteLn('Rate limited. Retry-After: ' + resp.GetHeaderField('Retry-After'));
        end;
      Exit;
    end;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a JSON object in the response.');
      Exit;
    end;
  if ((reply.JsonTypeOf('access_token') <> 1) or (reply.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Missing value: access_token');
      Exit;
    end;
  if ((reply.JsonTypeOf('refresh_token') <> 1) or (reply.StringOfEquals('refresh_token','',True) = True)) then
    begin
      WriteLn('Missing value: refresh_token');
      Exit;
    end;
  success := reply.WriteFile('jira-token.new.json');
  if (success <> True) then
    begin
      WriteLn('Could not save the rotated token; do not discard the response from memory.');
      Exit;
    end;
  success := reply.WriteFile('jira-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not update the token cache. Recover from jira-token.new.json; it contains the rotated token.');
      Exit;
    end;
  files := TFileAccess.Create;
  success := files.FileDelete('jira-token.new.json');
  if (success <> True) then
    begin
      WriteLn('Token cache updated, but the recovery copy could not be removed from the private directory.');
      Exit;
    end;
  WriteLn('Access and refresh tokens updated. Expires in seconds: ' + reply.IntOf('expires_in'));


  token.Free;
  request.Free;
  http.Free;
  resp.Free;
  reply.Free;
  files.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.