Sample code for 30+ languages & platforms
Objective-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 Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoDateTime.h>

BOOL success = NO;

CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
//  This example requires the Chilkat API to have been previously unlocked.
//  See Global.UnlockBundle for sample code.

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:30];
http.ReadTimeout = [NSNumber numberWithInt:60];
http.Accept = @"application/json";
CkoHttpResponse *response = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
//  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 = NO;
http.ProxyDomain = @"";
http.ConnectTimeout = [NSNumber numberWithInt:5];
http.ReadTimeout = [NSNumber numberWithInt:15];
CkoJsonObject *query = [[CkoJsonObject alloc] init];
[query UpdateString: @"api-version" value: @"2018-02-01"];
[query UpdateString: @"resource" value: @"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.
NSString *managedIdentityClientId = @"";
[stringCompare SetString: managedIdentityClientId];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch1 != YES) {
    [query UpdateString: @"client_id" value: managedIdentityClientId];
}

[http SetRequestHeader: @"Metadata" value: @"true"];
CkoDateTime *renewAt = [[CkoDateTime alloc] init];
success = [renewAt SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read the current time.");
    return;
}

success = [http HttpParams: @"GET" url: @"http://169.254.169.254/metadata/identity/oauth2/token" json: query response: response];
if ([response.StatusCode intValue] == 0) {
    NSLog(@"%@",@"No HTTP response. Inspect LastErrorText privately; it may contain credentials.");
    return;
}

if (([response.StatusCode intValue] != 200)) {
    NSLog(@"%@%d",@"HTTP status: ",[response.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[response GetHeaderField: @"x-ms-request-id"]);
    NSLog(@"%@%@",@"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 != YES) {
    NSLog(@"%@",@"The HTTP response could not be read completely.");
    return;
}

success = [result Load: response.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed JSON response.");
    return;
}

if ([[result JsonTypeOf: @"access_token"] intValue] != 1) {
    NSLog(@"%@",@"Missing or invalid access_token.");
    return;
}

if ([result StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES) {
    NSLog(@"%@",@"A nonempty access_token is required.");
    return;
}

if ([result StringOfEquals: @"token_type" value: @"Bearer" caseSensitive: NO] != YES) {
    NSLog(@"%@",@"Expected a Bearer token.");
    return;
}

//  IMDS may return expires_in as a string. Validate before converting to int.
CkoStringBuilder *lifetimeText = [[CkoStringBuilder alloc] init];
CkoStringBuilder *lifetimeCheck = [[CkoStringBuilder alloc] init];
[lifetimeText SetString: [result StringOf: @"expires_in"]];
int lifetime = [lifetimeText.IntValue intValue];
[lifetimeCheck AppendInt: [NSNumber numberWithInt: lifetime]];
if (([lifetimeText ContentsEqual: [lifetimeCheck GetAsString] caseSensitive: YES] != YES) || (lifetime <= 60) || (lifetime > 604800)) {
    NSLog(@"%@",@"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: [NSNumber numberWithInt: (lifetime - 60)]];
if (success != YES) {
    NSLog(@"%@",@"Could not calculate token renewal time.");
    return;
}

CkoJsonObject *saved = [[CkoJsonObject alloc] init];
[saved UpdateString: @"access_token" value: [result StringOf: @"access_token"]];
[saved UpdateString: @"token_type" value: @"Bearer"];
[saved UpdateInt: @"expires_in" value: [NSNumber numberWithInt: lifetime]];
[saved UpdateString: @"refresh_after_utc" value: [renewAt GetAsTimestamp: NO]];
//  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 != YES) {
    NSLog(@"%@",@"Could not save the private token file.");
    return;
}

NSLog(@"%@",@"Saved the ARM token without displaying it.");
NSLog(@"%@%@",@"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.