Azure Key Vault: Get a Token with Azure VM Managed Identity
See more Azure Key Vault Examples
Requires Chilkat 11.6.0 or later. Keep qa_data/azure/keyvault.json and token/PFX files private, outside web content and source control, with access restricted to the application identity. Use placeholders replaced by your configuration, never commit credentials. Create output directories before running file-writing examples. These examples target Azure public-cloud vaults, not Managed HSM or sovereign-cloud endpoints.
Run on an Azure VM with an enabled system-assigned identity, or set managed_identity_client_id for an attached user-assigned identity. The fixed link-local endpoint and Metadata header are specific to VM IMDS, not App Service. Proxying and redirects are disabled. Grant the identity appropriate vault data-plane permissions. Saves the same private token format as the other examples; does not print tokens. The example stops on IMDS errors; production IMDS retries must follow its service-specific guidance.
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>
BOOL success = NO;
CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
CkoJsonObject *config = [[CkoJsonObject alloc] init];
config.Strict = YES;
success = [config LoadFile: @"qa_data/azure/keyvault.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load private Key Vault configuration.");
return;
}
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:60];
http.VerboseLogging = NO;
CkoHttpRequest *request = [[CkoHttpRequest alloc] init];
request.HttpVerb = @"GET";
CkoHttpResponse *response = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
// Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
http.UseIEProxy = NO;
http.ProxyDomain = @"";
http.ConnectTimeout = [NSNumber numberWithInt:5];
request.HttpVerb = @"GET";
[request AddHeader: @"Metadata" value: @"true"];
[request AddParam: @"api-version" value: @"2018-02-01"];
[request AddParam: @"resource" value: @"https://vault.azure.net"];
if ([config HasMember: @"managed_identity_client_id"] == YES) {
[stringCompare SetString: [config StringOf: @"managed_identity_client_id"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"managed_identity_client_id"] intValue] != 1) || (stringMatch1 == YES)) {
NSLog(@"%@",@"Missing or invalid managed_identity_client_id.");
return;
}
[request AddParam: @"client_id" value: [config StringOf: @"managed_identity_client_id"]];
}
CkoDateTime *tokenExpires = [[CkoDateTime alloc] init];
success = [tokenExpires SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read time.");
return;
}
success = [http HttpReq: @"http://169.254.169.254/metadata/identity/oauth2/token" request: request response: response];
if (success != YES) {
NSLog(@"%@",@"IMDS request failed; run on an Azure VM with managed identity enabled.");
return;
}
if ([response.StatusCode intValue] != 200) {
NSLog(@"%@",@"Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.");
return;
}
success = [result Load: response.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Invalid JSON response.");
return;
}
[stringCompare SetString: [result StringOf: @"access_token"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || (stringMatch2 == YES)) {
NSLog(@"%@",@"Missing or invalid access_token.");
return;
}
[stringCompare SetString: [result StringOf: @"token_type"]];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"Bearer" caseSensitive: YES];
if (stringMatch3 != YES) {
NSLog(@"%@",@"Expected Bearer token.");
return;
}
if (([[result JsonTypeOf: @"expires_in"] intValue] != 2) && ([[result JsonTypeOf: @"expires_in"] intValue] != 1)) {
NSLog(@"%@",@"Missing token lifetime.");
return;
}
CkoStringBuilder *validate6 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet6 = [[CkoStringBuilder alloc] init];
success = [validate6 Append: [result StringOf: @"expires_in"]];
if (success != YES) {
NSLog(@"%@",@"Could not validate token lifetime.");
return;
}
success = [alphabet6 Append: @"0123456789"];
if (success != YES) {
NSLog(@"%@",@"Could not initialize validation.");
return;
}
if (([validate6.Length intValue] < 1) || ([validate6.Length intValue] > 8)) {
NSLog(@"%@",@"Invalid token lifetime length.");
return;
}
int charIndex6 = 0;
while ((charIndex6 < [validate6.Length intValue])) {
if ([alphabet6 Contains: [validate6 GetRange: [NSNumber numberWithInt: charIndex6] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid character in token lifetime.");
return;
}
charIndex6 = charIndex6 + 1;
}
int tokenLifetime = [[result IntOf: @"expires_in"] intValue];
if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
NSLog(@"%@",@"Unexpected token lifetime.");
return;
}
success = [tokenExpires AddSeconds: [NSNumber numberWithInt: tokenLifetime]];
if (success != YES) {
NSLog(@"%@",@"Could not calculate expiration.");
return;
}
CkoDateTime *tokenNow = [[CkoDateTime alloc] init];
success = [tokenNow SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read time.");
return;
}
if ([[tokenExpires DiffSeconds: tokenNow] intValue] <= 60) {
NSLog(@"%@",@"Token expired before it could be saved.");
return;
}
CkoJsonObject *saved = [[CkoJsonObject alloc] init];
success = [saved UpdateString: @"access_token" value: [result StringOf: @"access_token"]];
if (success != YES) {
NSLog(@"%@",@"Could not set access_token.");
return;
}
success = [saved UpdateString: @"expires_at" value: [tokenExpires GetAsTimestamp: NO]];
if (success != YES) {
NSLog(@"%@",@"Could not set expires_at.");
return;
}
success = [saved WriteFile: @"qa_data/tokens/azureKeyVaultToken.json"];
if (success != YES) {
NSLog(@"%@",@"Could not save the private token file.");
return;
}
NSLog(@"%@",@"Example completed.");