Sample code for 30+ languages & platforms
AutoIt 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 AutoIt Downloads

AutoIt
Local $bSuccess = False

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

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 30
$oHttp.ReadTimeout = 60
$oHttp.Accept = "application/json"
$oResponse = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
;  Private JSON configuration: tenant_id, client_id, client_secret (all strings).
;  Use a tenant directory ID, not common or consumers.
$oConfig = ObjCreate("Chilkat.JsonObject")
$oConfig.Strict = True
$bSuccess = $oConfig.LoadFile("qa_data/azure/arm-client.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load private Entra configuration." & @CRLF)
    Exit
EndIf

If ($oConfig.JsonTypeOf("tenant_id") <> 1) Then
    ConsoleWrite("Missing or invalid tenant_id." & @CRLF)
    Exit
EndIf

If ($oConfig.StringOfEquals("tenant_id","",True) = True) Then
    ConsoleWrite("A nonempty tenant_id is required." & @CRLF)
    Exit
EndIf

If ($oConfig.JsonTypeOf("client_id") <> 1) Then
    ConsoleWrite("Missing or invalid client_id." & @CRLF)
    Exit
EndIf

If ($oConfig.StringOfEquals("client_id","",True) = True) Then
    ConsoleWrite("A nonempty client_id is required." & @CRLF)
    Exit
EndIf

If ($oConfig.JsonTypeOf("client_secret") <> 1) Then
    ConsoleWrite("Missing or invalid client_secret." & @CRLF)
    Exit
EndIf

If ($oConfig.StringOfEquals("client_secret","",True) = True) Then
    ConsoleWrite("A nonempty client_secret is required." & @CRLF)
    Exit
EndIf

$bSuccess = $oHttp.SetUrlVar("tenant",$oConfig.StringOf("tenant_id"))
If ($bSuccess <> True) Then
    ConsoleWrite("Could not encode tenant." & @CRLF)
    Exit
EndIf

$oForm = ObjCreate("Chilkat.HttpRequest")
$oForm.HttpVerb = "POST"
$oForm.ContentType = "application/x-www-form-urlencoded"
;  AddParam performs form encoding, including +, &, and = in the secret.
$oForm.AddParam "grant_type","client_credentials"
$oForm.AddParam "client_id",$oConfig.StringOf("client_id")
$oForm.AddParam "client_secret",$oConfig.StringOf("client_secret")
$oForm.AddParam "scope","https://management.azure.com/.default"
$oRenewAt = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oRenewAt.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not read the current time." & @CRLF)
    Exit
EndIf

$bSuccess = $oHttp.HttpReq("https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token",$oForm,$oResponse)
If ($oResponse.StatusCode = 0) Then
    ConsoleWrite("No HTTP response. Inspect LastErrorText privately; it may contain credentials." & @CRLF)
    Exit
EndIf

If (($oResponse.StatusCode <> 200)) Then
    ConsoleWrite("HTTP status: " & $oResponse.StatusCode & @CRLF)
    ConsoleWrite("Request ID: " & $oResponse.GetHeaderField("x-ms-request-id") & @CRLF)
    ConsoleWrite("Retry-After: " & $oResponse.GetHeaderField("Retry-After") & @CRLF)
    ;  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
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("The HTTP response could not be read completely." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.Load($oResponse.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
    Exit
EndIf

If ($oResult.JsonTypeOf("access_token") <> 1) Then
    ConsoleWrite("Missing or invalid access_token." & @CRLF)
    Exit
EndIf

If ($oResult.StringOfEquals("access_token","",True) = True) Then
    ConsoleWrite("A nonempty access_token is required." & @CRLF)
    Exit
EndIf

If ($oResult.StringOfEquals("token_type","Bearer",False) <> True) Then
    ConsoleWrite("Expected a Bearer token." & @CRLF)
    Exit
EndIf

;  IMDS may return expires_in as a string. Validate before converting to int.
$oLifetimeText = ObjCreate("Chilkat.StringBuilder")
$oLifetimeCheck = ObjCreate("Chilkat.StringBuilder")
$oLifetimeText.SetString($oResult.StringOf("expires_in"))
Local $iLifetime = $oLifetimeText.IntValue
$oLifetimeCheck.AppendInt($iLifetime)
If (($oLifetimeText.ContentsEqual($oLifetimeCheck.GetAsString(),True) <> True) Or ($iLifetime <= 60) Or ($iLifetime > 604800)) Then
    ConsoleWrite("Invalid or unexpectedly short token lifetime." & @CRLF)
    Exit
EndIf

;  Start the lifetime at request start, not receipt, and renew at least a minute early.
$bSuccess = $oRenewAt.AddSeconds($iLifetime - 60)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not calculate token renewal time." & @CRLF)
    Exit
EndIf

$oSaved = ObjCreate("Chilkat.JsonObject")
$oSaved.UpdateString("access_token",$oResult.StringOf("access_token"))
$oSaved.UpdateString("token_type","Bearer")
$oSaved.UpdateInt("expires_in",$iLifetime)
$oSaved.UpdateString("refresh_after_utc",$oRenewAt.GetAsTimestamp(False))
;  Create qa_data/tokens beforehand with permissions limited to this application.
;  WriteFile does not create a secure directory or set operating-system ACLs.
$bSuccess = $oSaved.WriteFile("qa_data/tokens/azureToken.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save the private token file." & @CRLF)
    Exit
EndIf

ConsoleWrite("Saved the ARM token without displaying it." & @CRLF)
ConsoleWrite("Obtain a new token by UTC: " & $oSaved.StringOf("refresh_after_utc") & @CRLF)
;  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.