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 Unicode C++ Downloads
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkJsonObjectW.h>
#include <CkHttpRequestW.h>
#include <CkDateTimeW.h>
#include <CkStringBuilderW.h>
void ChilkatSample(void)
{
bool success = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(30);
http.put_ReadTimeout(60);
http.put_Accept(L"application/json");
CkHttpResponseW response;
CkJsonObjectW result;
result.put_Strict(true);
// Private JSON configuration: tenant_id, client_id, client_secret (all strings).
// Use a tenant directory ID, not common or consumers.
CkJsonObjectW config;
config.put_Strict(true);
success = config.LoadFile(L"qa_data/azure/arm-client.json");
if (success != true) {
wprintf(L"Could not load private Entra configuration.\n");
return;
}
if (config.JsonTypeOf(L"tenant_id") != 1) {
wprintf(L"Missing or invalid tenant_id.\n");
return;
}
if (config.StringOfEquals(L"tenant_id",L"",true) == true) {
wprintf(L"A nonempty tenant_id is required.\n");
return;
}
if (config.JsonTypeOf(L"client_id") != 1) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if (config.StringOfEquals(L"client_id",L"",true) == true) {
wprintf(L"A nonempty client_id is required.\n");
return;
}
if (config.JsonTypeOf(L"client_secret") != 1) {
wprintf(L"Missing or invalid client_secret.\n");
return;
}
if (config.StringOfEquals(L"client_secret",L"",true) == true) {
wprintf(L"A nonempty client_secret is required.\n");
return;
}
success = http.SetUrlVar(L"tenant",config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not encode tenant.\n");
return;
}
CkHttpRequestW form;
form.put_HttpVerb(L"POST");
form.put_ContentType(L"application/x-www-form-urlencoded");
// AddParam performs form encoding, including +, &, and = in the secret.
form.AddParam(L"grant_type",L"client_credentials");
form.AddParam(L"client_id",config.stringOf(L"client_id"));
form.AddParam(L"client_secret",config.stringOf(L"client_secret"));
form.AddParam(L"scope",L"https://management.azure.com/.default");
CkDateTimeW renewAt;
success = renewAt.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read the current time.\n");
return;
}
success = http.HttpReq(L"https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token",form,response);
if (response.get_StatusCode() == 0) {
wprintf(L"No HTTP response. Inspect LastErrorText privately; it may contain credentials.\n");
return;
}
if ((response.get_StatusCode() != 200)) {
wprintf(L"HTTP status: %d\n",response.get_StatusCode());
wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
wprintf(L"Retry-After: %s\n",response.getHeaderField(L"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;
}
if (success != true) {
wprintf(L"The HTTP response could not be read completely.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Expected a well-formed JSON response.\n");
return;
}
if (result.JsonTypeOf(L"access_token") != 1) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
if (result.StringOfEquals(L"access_token",L"",true) == true) {
wprintf(L"A nonempty access_token is required.\n");
return;
}
if (result.StringOfEquals(L"token_type",L"Bearer",false) != true) {
wprintf(L"Expected a Bearer token.\n");
return;
}
// IMDS may return expires_in as a string. Validate before converting to int.
CkStringBuilderW lifetimeText;
CkStringBuilderW lifetimeCheck;
lifetimeText.SetString(result.stringOf(L"expires_in"));
int lifetime = lifetimeText.get_IntValue();
lifetimeCheck.AppendInt(lifetime);
if ((lifetimeText.ContentsEqual(lifetimeCheck.getAsString(),true) != true) || (lifetime <= 60) || (lifetime > 604800)) {
wprintf(L"Invalid or unexpectedly short token lifetime.\n");
return;
}
// Start the lifetime at request start, not receipt, and renew at least a minute early.
success = renewAt.AddSeconds(lifetime - 60);
if (success != true) {
wprintf(L"Could not calculate token renewal time.\n");
return;
}
CkJsonObjectW saved;
saved.UpdateString(L"access_token",result.stringOf(L"access_token"));
saved.UpdateString(L"token_type",L"Bearer");
saved.UpdateInt(L"expires_in",lifetime);
saved.UpdateString(L"refresh_after_utc",renewAt.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.
success = saved.WriteFile(L"qa_data/tokens/azureToken.json");
if (success != true) {
wprintf(L"Could not save the private token file.\n");
return;
}
wprintf(L"Saved the ARM token without displaying it.\n");
wprintf(L"Obtain a new token by UTC: %s\n",saved.stringOf(L"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.
}