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

Visual Basic 6.0
Dim success As Long
success = 0

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

Dim http As New ChilkatHttp
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 30
http.ReadTimeout = 60
http.Accept = "application/json"
Dim response As New ChilkatHttpResponse
Dim result As New ChilkatJsonObject
result.Strict = 1
'  Private JSON configuration: tenant_id, client_id, client_secret (all strings).
'  Use a tenant directory ID, not common or consumers.
Dim config As New ChilkatJsonObject
config.Strict = 1
success = config.LoadFile("qa_data/azure/arm-client.json")
If (success <> 1) Then
    Debug.Print "Could not load private Entra configuration."
    Exit Sub
End If

If (config.JsonTypeOf("tenant_id") <> 1) Then
    Debug.Print "Missing or invalid tenant_id."
    Exit Sub
End If

If (config.StringOfEquals("tenant_id","",1) = 1) Then
    Debug.Print "A nonempty tenant_id is required."
    Exit Sub
End If

If (config.JsonTypeOf("client_id") <> 1) Then
    Debug.Print "Missing or invalid client_id."
    Exit Sub
End If

If (config.StringOfEquals("client_id","",1) = 1) Then
    Debug.Print "A nonempty client_id is required."
    Exit Sub
End If

If (config.JsonTypeOf("client_secret") <> 1) Then
    Debug.Print "Missing or invalid client_secret."
    Exit Sub
End If

If (config.StringOfEquals("client_secret","",1) = 1) Then
    Debug.Print "A nonempty client_secret is required."
    Exit Sub
End If

success = http.SetUrlVar("tenant",config.StringOf("tenant_id"))
If (success <> 1) Then
    Debug.Print "Could not encode tenant."
    Exit Sub
End If

Dim form As New ChilkatHttpRequest
form.HttpVerb = "POST"
form.ContentType = "application/x-www-form-urlencoded"
'  AddParam performs form encoding, including +, &, and = in the secret.
form.AddParam "grant_type","client_credentials"
form.AddParam "client_id",config.StringOf("client_id")
form.AddParam "client_secret",config.StringOf("client_secret")
form.AddParam "scope","https://management.azure.com/.default"
Dim renewAt As New CkDateTime
success = renewAt.SetFromCurrentSystemTime()
If (success <> 1) Then
    Debug.Print "Could not read the current time."
    Exit Sub
End If

success = http.HttpReq("https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token",form,response)
If (response.StatusCode = 0) Then
    Debug.Print "No HTTP response. Inspect LastErrorText privately; it may contain credentials."
    Exit Sub
End If

If ((response.StatusCode <> 200)) Then
    Debug.Print "HTTP status: " & response.StatusCode
    Debug.Print "Request ID: " & response.GetHeaderField("x-ms-request-id")
    Debug.Print "Retry-After: " & response.GetHeaderField("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 Sub
End If

If (success <> 1) Then
    Debug.Print "The HTTP response could not be read completely."
    Exit Sub
End If

success = result.Load(response.BodyStr)
If (success <> 1) Then
    Debug.Print "Expected a well-formed JSON response."
    Exit Sub
End If

If (result.JsonTypeOf("access_token") <> 1) Then
    Debug.Print "Missing or invalid access_token."
    Exit Sub
End If

If (result.StringOfEquals("access_token","",1) = 1) Then
    Debug.Print "A nonempty access_token is required."
    Exit Sub
End If

If (result.StringOfEquals("token_type","Bearer",0) <> 1) Then
    Debug.Print "Expected a Bearer token."
    Exit Sub
End If

'  IMDS may return expires_in as a string. Validate before converting to int.
Dim lifetimeText As New ChilkatStringBuilder
Dim lifetimeCheck As New ChilkatStringBuilder
success = lifetimeText.SetString(result.StringOf("expires_in"))
Dim lifetime As Long
lifetime = lifetimeText.IntValue
success = lifetimeCheck.AppendInt(lifetime)
If ((lifetimeText.ContentsEqual(lifetimeCheck.GetAsString(),1) <> 1) Or (lifetime <= 60) Or (lifetime > 604800)) Then
    Debug.Print "Invalid or unexpectedly short token lifetime."
    Exit Sub
End If

'  Start the lifetime at request start, not receipt, and renew at least a minute early.
success = renewAt.AddSeconds(lifetime - 60)
If (success <> 1) Then
    Debug.Print "Could not calculate token renewal time."
    Exit Sub
End If

Dim saved As New ChilkatJsonObject
success = saved.UpdateString("access_token",result.StringOf("access_token"))
success = saved.UpdateString("token_type","Bearer")
success = saved.UpdateInt("expires_in",lifetime)
success = saved.UpdateString("refresh_after_utc",renewAt.GetAsTimestamp(0))
'  Create qa_data/tokens beforehand with permissions limited to this application.
'  WriteFile does not create a secure directory or set operating-system ACLs.
success = saved.WriteFile("qa_data/tokens/azureToken.json")
If (success <> 1) Then
    Debug.Print "Could not save the private token file."
    Exit Sub
End If

Debug.Print "Saved the ARM token without displaying it."
Debug.Print "Obtain a new token by UTC: " & saved.StringOf("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.