Sample code for 30+ languages & platforms
C# Requires Chilkat v11.6.0+

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.

Microsoft API reference

Chilkat C# Downloads

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
//  This example requires the Chilkat API to have been previously unlocked.
//  See Global.UnlockBundle for sample code.

Chilkat.Http http = new Chilkat.Http();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
http.ConnectTimeout = 30;
http.ReadTimeout = 60;
http.Accept = "application/json";
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
Chilkat.JsonObject result = new Chilkat.JsonObject();
result.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.UseIEProxy = false;
http.ProxyDomain = "";
http.ConnectTimeout = 5;
http.ReadTimeout = 15;
Chilkat.JsonObject query = new Chilkat.JsonObject();
query.UpdateString("api-version","2018-02-01");
query.UpdateString("resource","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.
string managedIdentityClientId = "";
stringCompare.SetString(managedIdentityClientId);
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if (stringMatch1 != true) {
    query.UpdateString("client_id",managedIdentityClientId);
}

http.SetRequestHeader("Metadata","true");
Chilkat.CkDateTime renewAt = new Chilkat.CkDateTime();
success = renewAt.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read the current time.");
    return;
}

success = http.HttpParams("GET","http://169.254.169.254/metadata/identity/oauth2/token",query,response);
if (response.StatusCode == 0) {
    Debug.WriteLine("No HTTP response. Inspect LastErrorText privately; it may contain credentials.");
    return;
}

if ((response.StatusCode != 200)) {
    Debug.WriteLine("HTTP status: " + Convert.ToString(response.StatusCode));
    Debug.WriteLine("Request ID: " + response.GetHeaderField("x-ms-request-id"));
    Debug.WriteLine("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.
    return;
}

if (success != true) {
    Debug.WriteLine("The HTTP response could not be read completely.");
    return;
}

success = result.Load(response.BodyStr);
if (success != true) {
    Debug.WriteLine("Expected a well-formed JSON response.");
    return;
}

if (result.JsonTypeOf("access_token") != 1) {
    Debug.WriteLine("Missing or invalid access_token.");
    return;
}

if (result.StringOfEquals("access_token","",true) == true) {
    Debug.WriteLine("A nonempty access_token is required.");
    return;
}

if (result.StringOfEquals("token_type","Bearer",false) != true) {
    Debug.WriteLine("Expected a Bearer token.");
    return;
}

//  IMDS may return expires_in as a string. Validate before converting to int.
Chilkat.StringBuilder lifetimeText = new Chilkat.StringBuilder();
Chilkat.StringBuilder lifetimeCheck = new Chilkat.StringBuilder();
lifetimeText.SetString(result.StringOf("expires_in"));
int lifetime = lifetimeText.IntValue;
lifetimeCheck.AppendInt(lifetime);
if ((lifetimeText.ContentsEqual(lifetimeCheck.GetAsString(),true) != true) || (lifetime <= 60) || (lifetime > 604800)) {
    Debug.WriteLine("Invalid or unexpectedly short token lifetime.");
    return;
}

//  Start the lifetime at request start, not receipt, and renew at least a minute early.
success = renewAt.AddSeconds(lifetime - 60);
if (success != true) {
    Debug.WriteLine("Could not calculate token renewal time.");
    return;
}

Chilkat.JsonObject saved = new Chilkat.JsonObject();
saved.UpdateString("access_token",result.StringOf("access_token"));
saved.UpdateString("token_type","Bearer");
saved.UpdateInt("expires_in",lifetime);
saved.UpdateString("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("qa_data/tokens/azureToken.json");
if (success != true) {
    Debug.WriteLine("Could not save the private token file.");
    return;
}

Debug.WriteLine("Saved the ARM token without displaying it.");
Debug.WriteLine("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.