Azure Key Vault: Authenticate with a PS256 Certificate Assertion
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.
Register the public certificate as an application credential, then provide client_id, tenant_id and client_pfx_password. The authentication certificate is separate from certificates stored in the vault. Signs a short-lived PS256 JWT with x5t#S256, exact tenant token-endpoint audience, issuer/subject client ID and a random jti. Requires synchronized time. The secret-free exchange still requires protecting the local private key and returned token. Does not print the assertion.
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoCert.h>
#import <CkoPrivateKey.h>
#import <CkoBinData.h>
#import <NSString.h>
#import <CkoJwt.h>
#import <CkoPrng.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;
}
if ([[config JsonTypeOf: @"client_pfx_password"] intValue] != 1) {
NSLog(@"%@",@"Missing client_pfx_password string.");
return;
}
CkoCert *clientCert = [[CkoCert alloc] init];
success = [clientCert LoadPfxFile: @"qa_data/azure/client-auth.pfx" password: [config StringOf: @"client_pfx_password"]];
if (success != YES) {
NSLog(@"%@",@"Could not load client authentication PFX.");
return;
}
if ([clientCert IsRsa] != YES) {
NSLog(@"%@",@"PS256 client assertion requires RSA.");
return;
}
CkoPrivateKey *signingKey = [[CkoPrivateKey alloc] init];
success = [clientCert GetPrivateKey: signingKey];
if (success != YES) {
NSLog(@"%@",@"Client certificate needs a private key.");
return;
}
CkoBinData *certificateDer = [[CkoBinData alloc] init];
success = [certificateDer AppendEncoded: [clientCert GetEncoded] encoding: @"base64"];
if (success != YES) {
NSLog(@"%@",@"Could not encode client certificate.");
return;
}
NSString *thumbprint = [certificateDer GetHash: @"sha256" encoding: @"base64url"];
if (certificateDer.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not hash certificate.");
return;
}
CkoJsonObject *header = [[CkoJsonObject alloc] init];
CkoJsonObject *claims = [[CkoJsonObject alloc] init];
CkoJwt *jwt = [[CkoJwt alloc] init];
CkoPrng *random = [[CkoPrng alloc] init];
NSString *jwtId = [random GenRandom: [NSNumber numberWithInt: 32] encoding: @"hex"];
if (random.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not generate assertion ID.");
return;
}
success = [header UpdateString: @"alg" value: @"PS256"];
if (success != YES) {
NSLog(@"%@",@"Could not set alg.");
return;
}
success = [header UpdateString: @"typ" value: @"JWT"];
if (success != YES) {
NSLog(@"%@",@"Could not set typ.");
return;
}
success = [header UpdateString: @"x5t#S256" value: thumbprint];
if (success != YES) {
NSLog(@"%@",@"Could not set x5t#S256.");
return;
}
success = [claims UpdateString: @"iss" value: [config StringOf: @"client_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not set iss.");
return;
}
success = [claims UpdateString: @"sub" value: [config StringOf: @"client_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not set sub.");
return;
}
success = [claims UpdateString: @"aud" value: [tokenUrl GetAsString]];
if (success != YES) {
NSLog(@"%@",@"Could not set aud.");
return;
}
success = [claims UpdateString: @"jti" value: jwtId];
if (success != YES) {
NSLog(@"%@",@"Could not set jti.");
return;
}
success = [claims UpdateInt: @"nbf" value: [jwt GenNumericDate: [NSNumber numberWithInt: -30]]];
if (success != YES) {
NSLog(@"%@",@"Could not set assertion start.");
return;
}
success = [claims UpdateInt: @"iat" value: [jwt GenNumericDate: [NSNumber numberWithInt: 0]]];
if (success != YES) {
NSLog(@"%@",@"Could not set assertion issue time.");
return;
}
success = [claims UpdateInt: @"exp" value: [jwt GenNumericDate: [NSNumber numberWithInt: 300]]];
if (success != YES) {
NSLog(@"%@",@"Could not set assertion expiration.");
return;
}
NSString *assertion = [jwt CreateJwtPk: [header Emit] payload: [claims Emit] key: signingKey];
if (jwt.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not sign the client assertion.");
return;
}
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 *validate7 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet7 = [[CkoStringBuilder alloc] init];
success = [validate7 Append: [result StringOf: @"expires_in"]];
if (success != YES) {
NSLog(@"%@",@"Could not validate token lifetime.");
return;
}
success = [alphabet7 Append: @"0123456789"];
if (success != YES) {
NSLog(@"%@",@"Could not initialize validation.");
return;
}
if (([validate7.Length intValue] < 1) || ([validate7.Length intValue] > 8)) {
NSLog(@"%@",@"Invalid token lifetime length.");
return;
}
int charIndex7 = 0;
while ((charIndex7 < [validate7.Length intValue])) {
if ([alphabet7 Contains: [validate7 GetRange: [NSNumber numberWithInt: charIndex7] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid character in token lifetime.");
return;
}
charIndex7 = charIndex7 + 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.");