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

Outlook Contacts: Access Microsoft 365 Contacts with a Certificate

See more Outlook Contact Examples

Authenticate an unattended application with an RSA certificate and read contacts in one explicitly named Microsoft 365 mailbox. Upload the public certificate to the Entra app registration, grant Graph application Contacts.Read permission and administrator consent, and restrict mailbox access using supported Exchange application-access controls. Use Contacts.ReadWrite only for operations that require writes. Personal Outlook.com accounts do not support this app-only flow.

Private outlook-contacts-app.json contains tenant_id (directory ID), client_id (Application ID), mailbox (object ID or UPN), pfx_path, and pfx_password. Use an organizational tenant rather than common or consumers. Protect the private key in an application environment you control.

A fresh five-minute PS256 assertion includes the SHA-256 certificate thumbprint in x5t#S256. The assertion authenticates only to the tenant token endpoint; the returned access token goes to Graph. The .default scope uses administrator-granted application permissions. There is no refresh token: obtain a new access token with a new assertion when needed.

Follow the complete @odata.nextLink and retain the immutable-ID preference. The code checks the host, rejects repeated continuations, and has a stated 100-page demonstration limit. Save a continuation privately to resume a larger scan. IDs are opaque strings, and names or email addresses are not unique identifiers.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and contact data private.

Microsoft 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.CkDateTime,
  Chilkat.Crypt2,
  Chilkat.Jwt,
  Chilkat.StringBuilder,
  Chilkat.JsonObject,
  Chilkat.PrivateKey,
  Chilkat.HttpResponse,
  Chilkat.HttpRequest,
  Chilkat.Cert,
  Chilkat.StringArray,
  Chilkat.Http,
  Chilkat.BinData;

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

procedure RunDemo;
var
  success: Boolean;
  config: TJsonObject;
  http: THttp;
  tokenEndpoint: TStringBuilder;
  tokenUrl: string;
  cert: TCert;
  key: TPrivateKey;
  der: TBinData;
  crypt: TCrypt2;
  thumbprint: string;
  header: TJsonObject;
  claims: TJsonObject;
  assertionId: string;
  clock: TCkDateTime;
  jwt: TJwt;
  assertion: string;
  req: THttpRequest;
  resp: THttpResponse;
  result: TJsonObject;
  endpoint: TStringBuilder;
  url: string;
  nextLink: TStringBuilder;
  seenLinks: TStringArray;
  pageCount: Integer;
  i: Integer;
  nextType: Integer;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  success := False;
  config := TJsonObject.Create;
  config.Strict := True;
  success := config.LoadFile('outlook-contacts-app.json');
  if (success <> True) then
    begin
      WriteLn('Could not load private app configuration.');
      Exit;
    end;
  if ((config.JsonTypeOf('tenant_id') <> 1) or (config.StringOfEquals('tenant_id','',True) = True)) then
    begin
      WriteLn('Expected a nonempty tenant_id in the JSON.');
      Exit;
    end;
  if ((config.JsonTypeOf('client_id') <> 1) or (config.StringOfEquals('client_id','',True) = True)) then
    begin
      WriteLn('Expected a nonempty client_id in the JSON.');
      Exit;
    end;
  if ((config.JsonTypeOf('mailbox') <> 1) or (config.StringOfEquals('mailbox','',True) = True)) then
    begin
      WriteLn('Expected a nonempty mailbox in the JSON.');
      Exit;
    end;
  if ((config.JsonTypeOf('pfx_path') <> 1) or (config.StringOfEquals('pfx_path','',True) = True)) then
    begin
      WriteLn('Expected a nonempty pfx_path in the JSON.');
      Exit;
    end;
  //  pfx_password may be empty for an unencrypted test PFX; protect the private key in production.
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.FollowRedirects := False;
  http.ConnectTimeout := 20;
  http.ReadTimeout := 30;
  tokenEndpoint := TStringBuilder.Create;
  tokenEndpoint.Append('https://login.microsoftonline.com/');
  tokenEndpoint.Append(http.UrlEncode(config.StringOf('tenant_id')));
  tokenEndpoint.Append('/oauth2/v2.0/token');
  tokenUrl := tokenEndpoint.GetAsString();
  cert := TCert.Create;
  success := cert.LoadPfxFile(config.StringOf('pfx_path'),config.StringOf('pfx_password'));
  if (success <> True) then
    begin
      WriteLn('Could not load the application certificate.');
      Exit;
    end;
  key := TPrivateKey.Create;
  success := cert.GetPrivateKey(key);
  if (success <> True) then
    begin
      WriteLn('The certificate needs an accessible RSA private key.');
      Exit;
    end;
  der := TBinData.Create;
  success := cert.ExportCertDerBd(der);
  if (success <> True) then
    begin
      WriteLn('Could not read the certificate DER bytes.');
      Exit;
    end;
  crypt := TCrypt2.Create;
  crypt.HashAlgorithm := 'sha256';
  crypt.EncodingMode := 'base64url';
  thumbprint := crypt.HashBdENC(der);
  if (crypt.LastMethodSuccess <> True) then
    begin
      WriteLn('Could not hash the certificate.');
      Exit;
    end;
  header := TJsonObject.Create;
  header.UpdateString('alg','PS256');
  header.UpdateString('typ','JWT');
  header.UpdateString('x5t#S256',thumbprint);
  claims := TJsonObject.Create;
  claims.UpdateString('aud',tokenUrl);
  claims.UpdateString('iss',config.StringOf('client_id'));
  claims.UpdateString('sub',config.StringOf('client_id'));
  assertionId := crypt.GenerateUuid();
  if (crypt.LastMethodSuccess <> True) then
    begin
      WriteLn('Could not create the assertion ID.');
      Exit;
    end;
  claims.UpdateString('jti',assertionId);
  clock := TCkDateTime.Create;
  success := clock.SetFromCurrentSystemTime();
  if (success <> True) then
    begin
      WriteLn('Could not read the clock.');
      Exit;
    end;
  //  Numeric dates are JSON numbers built from decimal strings, without converting timestamps to a platform-sized integer.
  claims.UpdateNumber('iat',clock.GetAsUnixTimeStr(False));
  claims.UpdateNumber('nbf',clock.GetAsUnixTimeStr(False));
  success := clock.AddSeconds(300);
  if (success <> True) then
    begin
      WriteLn('Could not set assertion expiry.');
      Exit;
    end;
  claims.UpdateNumber('exp',clock.GetAsUnixTimeStr(False));
  jwt := TJwt.Create;
  assertion := jwt.CreateJwtPk(header.Emit(),claims.Emit(),key);
  if (jwt.LastMethodSuccess <> True) then
    begin
      WriteLn('Could not sign the client assertion.');
      Exit;
    end;
  req := THttpRequest.Create;
  req.HttpVerb := 'POST';
  req.ContentType := 'application/x-www-form-urlencoded';
  req.AddParam('client_id',config.StringOf('client_id'));
  req.AddParam('grant_type','client_credentials');
  req.AddParam('scope','https://graph.microsoft.com/.default');
  req.AddParam('client_assertion_type','urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
  req.AddParam('client_assertion',assertion);
  resp := THttpResponse.Create;
  result := TJsonObject.Create;
  result.Strict := True;
  success := http.HttpReq(tokenUrl,req,resp);
  //  A false result can still include an HTTP error response.
  if ((success <> True) and (resp.StatusCode = 0)) then
    begin
      WriteLn('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
      Exit;
    end;
  if (resp.StatusCode <> 200) then
    begin
      WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
      WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
      if (resp.StatusCode = 429) then
        begin
          WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
        end;
      if (resp.StatusCode = 401) then
        begin
          WriteLn('Refresh the Graph access token or authorize again.');
        end;
      Exit;
    end;
  success := result.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Expected a well-formed JSON response.');
      Exit;
    end;
  if ((result.JsonTypeOf('access_token') <> 1) or (result.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Expected a nonempty access_token in the JSON.');
      Exit;
    end;
  http.AuthToken := result.StringOf('access_token');
  //  Application tokens address an explicitly authorized mailbox, never /me.
  http.SetRequestHeader('Accept','application/json');
  http.SetRequestHeader('Prefer','IdType="ImmutableId"');
  endpoint := TStringBuilder.Create;
  endpoint.Append('https://graph.microsoft.com/v1.0/users/');
  endpoint.Append(http.UrlEncode(config.StringOf('mailbox')));
  endpoint.Append('/contacts?$select=id,displayName&$top=50');
  url := endpoint.GetAsString();
  nextLink := TStringBuilder.Create;
  seenLinks := TStringArray.Create;
  pageCount := 0;
  while (pageCount < 100) do
    begin
      //  Use Microsoft's nextLink exactly as returned; do not rebuild skip tokens.
      nextLink.Clear();
      nextLink.Append(url);
      if (nextLink.StartsWith('https://graph.microsoft.com/v1.0/',True) <> True) then
        begin
          WriteLn('Unexpected pagination host or API version; no request sent.');
          Exit;
        end;
      if (seenLinks.Find(url,0) >= 0) then
        begin
          WriteLn('Repeated pagination URL; stopping.');
          Exit;
        end;
      seenLinks.Append(url);
      success := http.HttpNoBody('GET',url,resp);
      //  A false result can still include an HTTP error response.
      if ((success <> True) and (resp.StatusCode = 0)) then
        begin
          WriteLn('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
          Exit;
        end;
      if (resp.StatusCode <> 200) then
        begin
          WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
          WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
          if (resp.StatusCode = 429) then
            begin
              WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
            end;
          if (resp.StatusCode = 401) then
            begin
              WriteLn('Refresh the Graph access token or authorize again.');
            end;
          Exit;
        end;
      success := result.Load(resp.BodyStr);
      if (success <> True) then
        begin
          WriteLn('Expected a well-formed JSON response.');
          Exit;
        end;
      if (result.JsonTypeOf('value') <> 4) then
        begin
          WriteLn('Expected a value array.');
          Exit;
        end;
      i := 0;
      while (i < result.SizeOfArray('value')) do
        begin
          result.I := i;
          if ((result.JsonTypeOf('value[i].id') <> 1) or (result.StringOfEquals('value[i].id','',True) = True)) then
            begin
              WriteLn('Expected a nonempty value[i].id in the JSON.');
              Exit;
            end;
          WriteLn('Contact ID: ' + result.StringOf('value[i].id'));
          WriteLn('Display name: ' + result.StringOf('value[i].displayName'));
          i := i + 1;
        end;

      pageCount := pageCount + 1;
      //  Quote the member name because @odata.nextLink contains a literal period.
      nextType := result.JsonTypeOf('"@odata.nextLink"');
      if ((nextType = -1) or (nextType = 6)) then
        begin
          WriteLn('Completed pages: ' + pageCount);
          Exit;
        end;
      if ((nextType <> 1) or (result.StringOfEquals('"@odata.nextLink"','',True) = True)) then
        begin
          WriteLn('Invalid continuation link; cannot establish completeness.');
          Exit;
        end;
      url := result.StringOf('"@odata.nextLink"');
    end;

  WriteLn('Stopped at the example''s 100-page limit. Save the continuation URL privately to resume.');


  config.Free;
  http.Free;
  tokenEndpoint.Free;
  cert.Free;
  key.Free;
  der.Free;
  crypt.Free;
  header.Free;
  claims.Free;
  clock.Free;
  jwt.Free;
  req.Free;
  resp.Free;
  result.Free;
  endpoint.Free;
  nextLink.Free;
  seenLinks.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.