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

Azure Storage Accounts: Obtain an ARM Token with Azure VM Managed Identity

See more Azure Storage Accounts Examples

Obtains an ARM token from Azure VM Instance Metadata Service (IMDS), without an application secret. Enable the VM's identity and assign it an Azure RBAC role covering the required storage-account management actions. Run this code inside that VM. App Service, Azure Arc, and other hosts have different identity endpoint contracts.

The fixed link-local endpoint uses HTTP by design. Do not proxy it, redirect it, or accept its address from user input. Set managedIdentityClientId to select a user-assigned identity attached to the VM, or leave it empty for a system-assigned identity. IMDS uses a resource parameter, not the v2 OAuth scope parameter.

The token is saved in private qa_data/tokens/azureToken.json. Rerun the IMDS request before the saved refresh_after_utc; do not use a refresh token. Protect the directory yourself and avoid printing the token. A VM hosting requirement does not mean this example needs a web server.

Microsoft API reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
http: HCkHttp;
response: HCkHttpResponse;
result: HCkJsonObject;
query: HCkJsonObject;
managedIdentityClientId: PWideChar;
stringMatch1: Boolean;
renewAt: HCkDateTime;
lifetimeText: HCkStringBuilder;
lifetimeCheck: HCkStringBuilder;
lifetime: Integer;
saved: HCkJsonObject;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  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);
//  Run on an Azure VM with managed identity enabled. This is not a public API.
//  IMDS deliberately uses a fixed link-local HTTP endpoint and must bypass proxies.
CkHttp_putUseIEProxy(http,False);
CkHttp_putProxyDomain(http,'');
CkHttp_putConnectTimeout(http,5);
CkHttp_putReadTimeout(http,15);
query := CkJsonObject_Create();
CkJsonObject_UpdateString(query,'api-version','2018-02-01');
CkJsonObject_UpdateString(query,'resource','https://management.azure.com/');
//  Empty selects the system-assigned identity. Set this to the CLIENT ID of an
//  identity assigned to the VM when selecting a user-assigned identity.
managedIdentityClientId := '';
CkStringBuilder_SetString(stringCompare,managedIdentityClientId);
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if (stringMatch1 <> True) then
  begin
    CkJsonObject_UpdateString(query,'client_id',managedIdentityClientId);
  end;
CkHttp_SetRequestHeader(http,'Metadata','true');
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_HttpParams(http,'GET','http://169.254.169.254/metadata/identity/oauth2/token',query,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.

CkStringBuilder_Dispose(stringCompare);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(query);
CkDateTime_Dispose(renewAt);
CkStringBuilder_Dispose(lifetimeText);
CkStringBuilder_Dispose(lifetimeCheck);
CkJsonObject_Dispose(saved);