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

Verify Okta ID Token Locally

See more Okta OAuth/OIDC Examples

This example demonstrates how to validate an Okta ID token using Chilkat's JWT class.

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.StringBuilder,
  Chilkat.PublicKey,
  Chilkat.Jwt,
  Chilkat.JsonObject,
  Chilkat.CkDateTime;

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

procedure RunDemo;
var
  success: Boolean;
  jsonToken: TJsonObject;
  jsonWebKeys: TJsonObject;
  jwt: TJwt;
  idToken: string;
  joseHeader: string;
  json: TJsonObject;
  kid: string;
  sbKid: TStringBuilder;
  e: string;
  n: string;
  i: Integer;
  count_i: Integer;
  bFound: Boolean;
  iMatch: Integer;
  pubkey: TPublicKey;
  jsonWebKey: TJsonObject;
  bVerified: Boolean;
  claims: string;
  jsonClaims: TJsonObject;
  dtExp: TCkDateTime;
  bExpired: Boolean;

begin
  success := False;

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

  //  This example begins with two JSON files:
  //  
  //  1. The access + id token obtained from Okta as shown in one fo these examples:  
  //     Get Okta Token using Resource Owner Password Flow
  //  
  //  2. The Okta web keys obtained by this example:  Get Okta Web Keys
  //  
  //  

  //  ----------------------------------------------------------------
  //  Note: The very last step of this example is where the claims, such as iss, aud, iat, exp, and nonce
  //  are extracted from the ID token and examined.
  //  ----------------------------------------------------------------

  //  Load the access/id token to be verified.
  //  It contains JSON that looks like this:
  //  {
  //    "access_token": "eyJraWQiOiJhb ... O_eVu-kBp6g",
  //    "token_type": "Bearer",
  //    "expires_in": 3600,
  //    "scope": "openid",
  //    "id_token": "eyJraWQi ... FrL9WOuwbQtUg"
  //  }
  //  This example verifies the id_token.  (The access_token is verified in this example:  Verify Okta Access Token

  jsonToken := TJsonObject.Create;
  success := jsonToken.LoadFile('qa_data/tokens/okta_access_token.json');

  //  Load the public keys (Okta web keys), one of which is needed to validate.
  //  The web keys JSON looks like this:
  //  {
  //    "keys": [
  //      {
  //        "kty": "RSA",
  //        "alg": "RS256",
  //        "kid": "anSaRDPfWGOSCVNZEIZB9quCbNsdsvl5uWGBzxbudWQ",
  //        "use": "sig",
  //        "e": "AQAB",
  //        "n": "jT8uAgd5w ... euLB1HaVw"
  //      },
  //      {
  //  	...
  //      }
  //    ]
  //  }

  jsonWebKeys := TJsonObject.Create;
  success := jsonWebKeys.LoadFile('qa_data/tokens/okta_web_keys.json');

  //  ------------------------
  //  Step 1: Get the JOSE header from the JWT.  The JOSE header contains JSON.  One of the JSON members will be the key ID "kid" which identifies the web key to be used for validation.
  //  
  jwt := TJwt.Create;
  idToken := jsonToken.StringOf('id_token');
  joseHeader := jwt.GetHeader(idToken);

  WriteLn(joseHeader);
  //  The joseHeader contains this:   {"kid":"anSaRDPfWGOSCVNZEIZB9quCbNsdsvl5uWGBzxbudWQ","alg":"RS256"}

  json := TJsonObject.Create;
  json.Load(joseHeader);
  kid := json.StringOf('kid');
  WriteLn('kid to find: ' + kid);

  //  ------------------------
  //  Step 2: Find the key with the same "kid" in the Okta web keys.

  sbKid := TStringBuilder.Create;
  e := '';
  n := '';

  i := 0;
  count_i := jsonWebKeys.SizeOfArray('keys');
  bFound := False;
  iMatch := 0;
  while (bFound = False) and (i < count_i) do
    begin
      jsonWebKeys.I := i;
      sbKid.Clear();
      jsonWebKeys.StringOfSb('keys[i].kid',sbKid);
      WriteLn('checking kid: ' + sbKid.GetAsString());

      if (sbKid.ContentsEqual(kid,True) = True) then
        begin
          e := jsonWebKeys.StringOf('keys[i].e');
          n := jsonWebKeys.StringOf('keys[i].n');
          //  Exit the loop. 
          WriteLn('Found matching kid.');
          iMatch := i;
          bFound := True;
        end;
      i := i + 1;
    end;

  if (bFound = False) then
    begin
      WriteLn('No matching key ID found.');
      Exit;
    end;

  WriteLn('Matching key:');
  WriteLn('  exponent = ' + e);
  WriteLn('  modulus = ' + n);

  //  ------------------------
  //  Step 3: Load the RSA modulus and exponent into a Chilkat public key object.
  pubkey := TPublicKey.Create;

  //  Get the matching JSON key from the array of keys.
  jsonWebKeys.I := iMatch;

  jsonWebKey := TJsonObject.Create;
  jsonWebKeys.ObjectOf2('keys[i]',jsonWebKey);

  success := pubkey.LoadFromString(jsonWebKey.Emit());
  if (success = False) then
    begin
      WriteLn('Failed to load JSON web key.');
      WriteLn(jsonWebKey.Emit());
      WriteLn(pubkey.LastErrorText);
      Exit;
    end;
  WriteLn('successfully loaded web key.');

  //  OK.. we have the desired JSON web key loaded into our public key object.
  //  Now we can verify the access token.

  //  ------------------------
  //  Step 4: Verify the access token.
  bVerified := jwt.VerifyJwtPk(idToken,pubkey);
  if (bVerified = True) then
    begin
      WriteLn('The ID token is valid.');
    end
  else
    begin
      WriteLn('The ID token is NOT valid.');
    end;

  //  ------------------------
  //  Step 5: Extract the claims (payload) from the ID token and examine them..

  claims := jwt.GetPayload(idToken);

  jsonClaims := TJsonObject.Create;
  jsonClaims.Load(claims);
  jsonClaims.EmitCompact := False;
  WriteLn(jsonClaims.Emit());

  //  Sample claims:
  //  {
  //    "sub": "00utrr8ehubooPhjj356",
  //    "ver": 1,
  //    "iss": "https://dev-765951.okta.com/oauth2/default",
  //    "aud": "0oatrr20vPYgVDlGr356",
  //    "iat": 1562190727,
  //    "exp": 1562194327,
  //    "jti": "ID.JvlMhlnCj5ZqqGjk-jlgcOxHEyVUwIl9_Kpz69U2D_4",
  //    "amr": [
  //      "pwd"
  //    ],
  //    "idp": "00os29azljkqyx99Q356",
  //    "auth_time": 1562190726,
  //    "at_hash": "SLMiVeyNWWEDaZ-O32nKMg"
  //  }

  //  The exp (expiry time) claim is the time at which this token will expire., expressed in Unix time. You should make sure that this time has not already passed.
  dtExp := TCkDateTime.Create;
  dtExp.SetFromUnixTime(False,jsonClaims.IntOf('exp'));
  WriteLn('expire timestamp = ' + dtExp.GetAsTimestamp(False));

  //  Check to see if this date/time expires within 0 seconds (i.e. is already past)
  bExpired := dtExp.ExpiresWithin(0,'seconds');
  WriteLn('bExpired = ' + bExpired);


  jsonToken.Free;
  jsonWebKeys.Free;
  jwt.Free;
  json.Free;
  sbKid.Free;
  pubkey.Free;
  jsonWebKey.Free;
  jsonClaims.Free;
  dtExp.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.