Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

Azure Storage Accounts: Obtain and Renew an ARM Token with Client Credentials

See more Azure Storage Accounts Examples

Obtains an Azure Resource Manager token with a tenant-specific v2 OAuth request and saves it for the account examples. Configure an Entra application and assign its service principal the required Azure RBAC role at the intended scope. The scope is https://management.azure.com/.default; a Storage or Graph audience is different.

Place tenant_id, client_id, and client_secret in private qa_data/azure/arm-client.json. Use the secret value, not its identifier. This is suitable for controlled applications that can protect credentials, not a secret embedded in a publicly distributed app. A certificate or federated credential is another authentication option.

The saved refresh_after_utc is a renewal deadline with a one-minute margin. Schedule another client-credentials request before it; this flow issues no refresh token. The sample obtains a new token each run and checks the write. Protect the output directory with OS permissions, and use atomic replacement/coordination if multiple processes share the token file.

Microsoft API reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
http: HCkHttp;
response: HCkHttpResponse;
result: HCkJsonObject;
config: HCkJsonObject;
form: HCkHttpRequest;
renewAt: HCkDateTime;
lifetimeText: HCkStringBuilder;
lifetimeCheck: HCkStringBuilder;
lifetime: Integer;
saved: HCkJsonObject;

begin
success := False;

//  This example requires the Chilkat API to have been previously unlocked.
//  See Global.UnlockBundle for sample code.

http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,30);
CkHttp_putReadTimeout(http,60);
CkHttp_putAccept(http,'application/json');
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
//  Private JSON configuration: tenant_id, client_id, client_secret (all strings).
//  Use a tenant directory ID, not common or consumers.
config := CkJsonObject_Create();
CkJsonObject_putStrict(config,True);
success := CkJsonObject_LoadFile(config,'qa_data/azure/arm-client.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private Entra configuration.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(config,'tenant_id') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid tenant_id.');
    Exit;
  end;
if (CkJsonObject_StringOfEquals(config,'tenant_id','',True) = True) then
  begin
    Memo1.Lines.Add('A nonempty tenant_id is required.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(config,'client_id') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if (CkJsonObject_StringOfEquals(config,'client_id','',True) = True) then
  begin
    Memo1.Lines.Add('A nonempty client_id is required.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(config,'client_secret') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid client_secret.');
    Exit;
  end;
if (CkJsonObject_StringOfEquals(config,'client_secret','',True) = True) then
  begin
    Memo1.Lines.Add('A nonempty client_secret is required.');
    Exit;
  end;
success := CkHttp_SetUrlVar(http,'tenant',CkJsonObject__stringOf(config,'tenant_id'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode tenant.');
    Exit;
  end;

form := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(form,'POST');
CkHttpRequest_putContentType(form,'application/x-www-form-urlencoded');
//  AddParam performs form encoding, including +, &, and = in the secret.
CkHttpRequest_AddParam(form,'grant_type','client_credentials');
CkHttpRequest_AddParam(form,'client_id',CkJsonObject__stringOf(config,'client_id'));
CkHttpRequest_AddParam(form,'client_secret',CkJsonObject__stringOf(config,'client_secret'));
CkHttpRequest_AddParam(form,'scope','https://management.azure.com/.default');
renewAt := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(renewAt);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read the current time.');
    Exit;
  end;

success := CkHttp_HttpReq(http,'https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token',form,response);
if (CkHttpResponse_getStatusCode(response) = 0) then
  begin
    Memo1.Lines.Add('No HTTP response. Inspect LastErrorText privately; it may contain credentials.');
    Exit;
  end;
if ((CkHttpResponse_getStatusCode(response) <> 200)) then
  begin
    Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(response)));
    Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(response,'x-ms-request-id'));
    Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
    //  Inspect the error body privately. Do not log tokens, headers, or full responses.
    //  For 401 check the token/audience; for 403 check Azure RBAC and policy.
    //  Honor Retry-After for 429 and use bounded backoff for transient failures.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('The HTTP response could not be read completely.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a well-formed JSON response.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(result,'access_token') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid access_token.');
    Exit;
  end;
if (CkJsonObject_StringOfEquals(result,'access_token','',True) = True) then
  begin
    Memo1.Lines.Add('A nonempty access_token is required.');
    Exit;
  end;
if (CkJsonObject_StringOfEquals(result,'token_type','Bearer',False) <> True) then
  begin
    Memo1.Lines.Add('Expected a Bearer token.');
    Exit;
  end;
//  IMDS may return expires_in as a string. Validate before converting to int.
lifetimeText := CkStringBuilder_Create();
lifetimeCheck := CkStringBuilder_Create();
CkStringBuilder_SetString(lifetimeText,CkJsonObject__stringOf(result,'expires_in'));
lifetime := CkStringBuilder_getIntValue(lifetimeText);
CkStringBuilder_AppendInt(lifetimeCheck,lifetime);
if ((CkStringBuilder_ContentsEqual(lifetimeText,CkStringBuilder__getAsString(lifetimeCheck),True) <> True) or (lifetime <= 60) or (lifetime > 604800)) then
  begin
    Memo1.Lines.Add('Invalid or unexpectedly short token lifetime.');
    Exit;
  end;
//  Start the lifetime at request start, not receipt, and renew at least a minute early.
success := CkDateTime_AddSeconds(renewAt,lifetime - 60);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not calculate token renewal time.');
    Exit;
  end;

saved := CkJsonObject_Create();
CkJsonObject_UpdateString(saved,'access_token',CkJsonObject__stringOf(result,'access_token'));
CkJsonObject_UpdateString(saved,'token_type','Bearer');
CkJsonObject_UpdateInt(saved,'expires_in',lifetime);
CkJsonObject_UpdateString(saved,'refresh_after_utc',CkDateTime__getAsTimestamp(renewAt,False));
//  Create qa_data/tokens beforehand with permissions limited to this application.
//  WriteFile does not create a secure directory or set operating-system ACLs.
success := CkJsonObject_WriteFile(saved,'qa_data/tokens/azureToken.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the private token file.');
    Exit;
  end;

Memo1.Lines.Add('Saved the ARM token without displaying it.');
Memo1.Lines.Add('Obtain a new token by UTC: ' + CkJsonObject__stringOf(saved,'refresh_after_utc'));
//  A scheduler can rerun this token request before refresh_after_utc.
//  These app-only flows do not use an OAuth refresh_token.
//  The other account examples read this file and set http.AuthToken.

CkHttp_Dispose(http);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(config);
CkHttpRequest_Dispose(form);
CkDateTime_Dispose(renewAt);
CkStringBuilder_Dispose(lifetimeText);
CkStringBuilder_Dispose(lifetimeCheck);
CkJsonObject_Dispose(saved);