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.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkJsonObjectW.h>
#include <CkDateTimeW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// 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);
// 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.
http.put_UseIEProxy(false);
http.put_ProxyDomain(L"");
http.put_ConnectTimeout(5);
http.put_ReadTimeout(15);
CkJsonObjectW query;
query.UpdateString(L"api-version",L"2018-02-01");
query.UpdateString(L"resource",L"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.
const wchar_t *managedIdentityClientId = L"";
stringCompare.SetString(managedIdentityClientId);
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if (stringMatch1 != true) {
query.UpdateString(L"client_id",managedIdentityClientId);
}
http.SetRequestHeader(L"Metadata",L"true");
CkDateTimeW renewAt;
success = renewAt.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read the current time.\n");
return;
}
success = http.HttpParams(L"GET",L"http://169.254.169.254/metadata/identity/oauth2/token",query,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.
}