Azure Key Vault: Exchange a Workload Identity Token
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.
Configure an Entra federated identity credential with the exact external issuer, subject, and audience (commonly api://AzureADTokenExchange). Provide client_id and tenant_id. Have the trusted workload runtime supply a fresh projected JWT at qa_data/azure/federated-token.jwt before each exchange; adapt this path to your runtime-provided token path. The application forwards this assertion to the fixed tenant endpoint; Entra validates the federation trust. This does not mint or locally trust an arbitrary external token.
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <NSString.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;
}
[stringCompare SetString: [config StringOf: @"client_id"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"client_id"] intValue] != 1) || (stringMatch1 == YES)) {
NSLog(@"%@",@"Missing or invalid client_id.");
return;
}
[stringCompare SetString: [config StringOf: @"tenant_id"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"tenant_id"] intValue] != 1) || (stringMatch2 == YES)) {
NSLog(@"%@",@"Missing or invalid tenant_id.");
return;
}
CkoStringBuilder *validate5 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet5 = [[CkoStringBuilder alloc] init];
success = [validate5 Append: [config StringOf: @"tenant_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not validate tenant GUID.");
return;
}
success = [alphabet5 Append: @"0123456789abcdefABCDEF-"];
if (success != YES) {
NSLog(@"%@",@"Could not initialize validation.");
return;
}
if (([validate5.Length intValue] < 36) || ([validate5.Length intValue] > 36)) {
NSLog(@"%@",@"Invalid tenant GUID length.");
return;
}
int charIndex5 = 0;
while ((charIndex5 < [validate5.Length intValue])) {
if ([alphabet5 Contains: [validate5 GetRange: [NSNumber numberWithInt: charIndex5] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid character in tenant GUID.");
return;
}
charIndex5 = charIndex5 + 1;
}
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;
CkoStringBuilder *tokenUrl = [[CkoStringBuilder alloc] init];
success = [tokenUrl Append: @"https://login.microsoftonline.com/"];
if (success != YES) {
NSLog(@"%@",@"Could not construct URL or identifier.");
return;
}
success = [tokenUrl Append: [config StringOf: @"tenant_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not construct URL or identifier.");
return;
}
success = [tokenUrl Append: @"/oauth2/v2.0/token"];
if (success != YES) {
NSLog(@"%@",@"Could not construct URL or identifier.");
return;
}
// Your trusted workload runtime must refresh this projected token file.
CkoStringBuilder *projected = [[CkoStringBuilder alloc] init];
success = [projected LoadFile: @"qa_data/azure/federated-token.jwt" charset: @"utf-8"];
if (success != YES) {
NSLog(@"%@",@"Could not read projected workload token.");
return;
}
success = [projected Trim];
if (success != YES) {
NSLog(@"%@",@"Could not trim token.");
return;
}
if ([projected.Length intValue] == 0) {
NSLog(@"%@",@"Projected token is empty.");
return;
}
NSString *assertion = [projected GetAsString];
request.HttpVerb = @"POST";
request.ContentType = @"application/x-www-form-urlencoded";
[request AddParam: @"client_id" value: [config StringOf: @"client_id"]];
[request AddParam: @"scope" value: @"https://vault.azure.net/.default"];
[request AddParam: @"grant_type" value: @"client_credentials"];
[request AddParam: @"client_assertion_type" value: @"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"];
[request AddParam: @"client_assertion" value: assertion];
CkoDateTime *tokenExpires = [[CkoDateTime alloc] init];
success = [tokenExpires SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read time.");
return;
}
success = [http HttpReq: [tokenUrl GetAsString] request: request response: response];
if (success != YES) {
NSLog(@"%@",@"Token exchange failed; inspect diagnostics privately.");
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 stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || (stringMatch3 == YES)) {
NSLog(@"%@",@"Missing or invalid access_token.");
return;
}
[stringCompare SetString: [result StringOf: @"token_type"]];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"Bearer" caseSensitive: YES];
if (stringMatch4 != YES) {
NSLog(@"%@",@"Expected Bearer token.");
return;
}
if (([[result JsonTypeOf: @"expires_in"] intValue] != 2)) {
NSLog(@"%@",@"Missing token lifetime.");
return;
}
CkoStringBuilder *validate8 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet8 = [[CkoStringBuilder alloc] init];
success = [validate8 Append: [result StringOf: @"expires_in"]];
if (success != YES) {
NSLog(@"%@",@"Could not validate token lifetime.");
return;
}
success = [alphabet8 Append: @"0123456789"];
if (success != YES) {
NSLog(@"%@",@"Could not initialize validation.");
return;
}
if (([validate8.Length intValue] < 1) || ([validate8.Length intValue] > 8)) {
NSLog(@"%@",@"Invalid token lifetime length.");
return;
}
int charIndex8 = 0;
while ((charIndex8 < [validate8.Length intValue])) {
if ([alphabet8 Contains: [validate8 GetRange: [NSNumber numberWithInt: charIndex8] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid character in token lifetime.");
return;
}
charIndex8 = charIndex8 + 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.");