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 Objective-C Downloads
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoJsonObject.h>
#import <CkoHttpRequest.h>
#import <CkoDateTime.h>
#import <CkoStringBuilder.h>
BOOL success = NO;
// 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;
// Private JSON configuration: tenant_id, client_id, client_secret (all strings).
// Use a tenant directory ID, not common or consumers.
CkoJsonObject *config = [[CkoJsonObject alloc] init];
config.Strict = YES;
success = [config LoadFile: @"qa_data/azure/arm-client.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load private Entra configuration.");
return;
}
if ([[config JsonTypeOf: @"tenant_id"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid tenant_id.");
return;
}
if ([config StringOfEquals: @"tenant_id" value: @"" caseSensitive: YES] == YES) {
NSLog(@"%@",@"A nonempty tenant_id is required.");
return;
}
if ([[config JsonTypeOf: @"client_id"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid client_id.");
return;
}
if ([config StringOfEquals: @"client_id" value: @"" caseSensitive: YES] == YES) {
NSLog(@"%@",@"A nonempty client_id is required.");
return;
}
if ([[config JsonTypeOf: @"client_secret"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid client_secret.");
return;
}
if ([config StringOfEquals: @"client_secret" value: @"" caseSensitive: YES] == YES) {
NSLog(@"%@",@"A nonempty client_secret is required.");
return;
}
success = [http SetUrlVar: @"tenant" value: [config StringOf: @"tenant_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not encode tenant.");
return;
}
CkoHttpRequest *form = [[CkoHttpRequest alloc] init];
form.HttpVerb = @"POST";
form.ContentType = @"application/x-www-form-urlencoded";
// AddParam performs form encoding, including +, &, and = in the secret.
[form AddParam: @"grant_type" value: @"client_credentials"];
[form AddParam: @"client_id" value: [config StringOf: @"client_id"]];
[form AddParam: @"client_secret" value: [config StringOf: @"client_secret"]];
[form AddParam: @"scope" value: @"https://management.azure.com/.default"];
CkoDateTime *renewAt = [[CkoDateTime alloc] init];
success = [renewAt SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read the current time.");
return;
}
success = [http HttpReq: @"https://login.microsoftonline.com/{$tenant}/oauth2/v2.0/token" request: form 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.