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.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global.UnlockBundle for sample code.
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 30
http.read_timeout = 60
http.accept = "application/json"
local response = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
-- Private JSON configuration: tenant_id, client_id, client_secret (all strings).
-- Use a tenant directory ID, not common or consumers.
local config = chilkat.JsonObject.new()
config.strict = true
local success = config:load_file("qa_data/azure/arm-client.json")
if not success then
print("Could not load private Entra configuration.")
return
end
if config:json_type_of("tenant_id") ~= 1 then
print("Missing or invalid tenant_id.")
return
end
if config:string_of_equals("tenant_id", "", true) then
print("A nonempty tenant_id is required.")
return
end
if config:json_type_of("client_id") ~= 1 then
print("Missing or invalid client_id.")
return
end
if config:string_of_equals("client_id", "", true) then
print("A nonempty client_id is required.")
return
end
if config:json_type_of("client_secret") ~= 1 then
print("Missing or invalid client_secret.")
return
end
if config:string_of_equals("client_secret", "", true) then
print("A nonempty client_secret is required.")
return
end
success = http:set_url_var("tenant", config:string_of("tenant_id"))
if not success then
print("Could not encode tenant.")
return
end
local form = chilkat.HttpRequest.new()
form.http_verb = "POST"
form.content_type = "application/x-www-form-urlencoded"
-- AddParam performs form encoding, including +, &, and = in the secret.
form:add_param("grant_type", "client_credentials")
form:add_param("client_id", config:string_of("client_id"))
form:add_param("client_secret", config:string_of("client_secret"))
form:add_param("scope", "https://management.azure.com/.default")
local renewAt = chilkat.DateTime.new()
success = renewAt:set_from_current_system_time()
if not success then
print("Could not read the current time.")
return
end
success = http:http_req("https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token", form, response)
if response.status_code == 0 then
print("No HTTP response. Inspect LastErrorText privately; it may contain credentials.")
return
end
if response.status_code ~= 200 then
print("HTTP status: " .. response.status_code)
print("Request ID: " .. response:get_header_field("x-ms-request-id"))
print("Retry-After: " .. response:get_header_field("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.
return
end
if not success then
print("The HTTP response could not be read completely.")
return
end
success = result:load(response.body_str)
if not success then
print("Expected a well-formed JSON response.")
return
end
if result:json_type_of("access_token") ~= 1 then
print("Missing or invalid access_token.")
return
end
if result:string_of_equals("access_token", "", true) then
print("A nonempty access_token is required.")
return
end
if not result:string_of_equals("token_type", "Bearer", false) then
print("Expected a Bearer token.")
return
end
-- IMDS may return expires_in as a string. Validate before converting to int.
local lifetimeText = chilkat.StringBuilder.new()
local lifetimeCheck = chilkat.StringBuilder.new()
lifetimeText:set_string(result:string_of("expires_in"))
local lifetime = lifetimeText.int_value
lifetimeCheck:append_int(lifetime)
if (not lifetimeText:contents_equal(lifetimeCheck:get_as_string(), true)) or ((lifetime <= 60) or (lifetime > 604800)) then
print("Invalid or unexpectedly short token lifetime.")
return
end
-- Start the lifetime at request start, not receipt, and renew at least a minute early.
success = renewAt:add_seconds(lifetime - 60)
if not success then
print("Could not calculate token renewal time.")
return
end
local saved = chilkat.JsonObject.new()
saved:update_string("access_token", result:string_of("access_token"))
saved:update_string("token_type", "Bearer")
saved:update_int("expires_in", lifetime)
saved:update_string("refresh_after_utc", renewAt:get_as_timestamp(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 = saved:write_file("qa_data/tokens/azureToken.json")
if not success then
print("Could not save the private token file.")
return
end
print("Saved the ARM token without displaying it.")
print("Obtain a new token by UTC: " .. saved:string_of("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.