Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

Azure Key Vault: Get an OAuth2 Token with Client Credentials

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.

Uses the Microsoft Entra v2 tenant-specific token endpoint and https://vault.azure.net/.default scope. Set nonempty client_id, client_secret, and directory GUID tenant_id in the private configuration. Use the client secret VALUE, not its identifier. This is for confidential applications, never browser/mobile clients. Client credentials have no refresh token: request another access token when needed. The token file is plaintext and must be protected by OS permissions. Token issuance does not grant vault access; grant only the required data-plane permissions to the service principal through Azure RBAC or the vault's configured access-policy model. Contributor alone does not grant data-plane access. Prefer managed identity or workload federation where available.

Microsoft reference

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>
#import <NSString.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: @"client_secret"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"client_secret"] intValue] != 1) || (stringMatch2 == YES)) {
    NSLog(@"%@",@"Missing or invalid client_secret.");
    return;
}

[stringCompare SetString: [config StringOf: @"tenant_id"]];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"tenant_id"] intValue] != 1) || (stringMatch3 == YES)) {
    NSLog(@"%@",@"Missing or invalid tenant_id.");
    return;
}

CkoStringBuilder *validate4 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet4 = [[CkoStringBuilder alloc] init];
success = [validate4 Append: [config StringOf: @"tenant_id"]];
if (success != YES) {
    NSLog(@"%@",@"Could not validate tenant GUID.");
    return;
}

success = [alphabet4 Append: @"0123456789abcdefABCDEF-"];
if (success != YES) {
    NSLog(@"%@",@"Could not initialize validation.");
    return;
}

if (([validate4.Length intValue] < 36) || ([validate4.Length intValue] > 36)) {
    NSLog(@"%@",@"Invalid tenant GUID length.");
    return;
}

int charIndex4 = 0;
while ((charIndex4 < [validate4.Length intValue])) {
    if ([alphabet4 Contains: [validate4 GetRange: [NSNumber numberWithInt: charIndex4] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Invalid character in tenant GUID.");
        return;
    }

    charIndex4 = charIndex4 + 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;
}

request.HttpVerb = @"POST";
request.ContentType = @"application/x-www-form-urlencoded";
[request AddParam: @"client_id" value: [config StringOf: @"client_id"]];
[request AddParam: @"client_secret" value: [config StringOf: @"client_secret"]];
[request AddParam: @"scope" value: @"https://vault.azure.net/.default"];
[request AddParam: @"grant_type" value: @"client_credentials"];
//  Use request-start time so network latency cannot extend the cached lifetime.
CkoDateTime *expires = [[CkoDateTime alloc] init];
success = [expires SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read current time.");
    return;
}

success = [http HttpReq: [tokenUrl GetAsString] request: request response: response];
if (success != YES) {
    NSLog(@"%@",@"Token request failed; inspect diagnostics privately.");
    return;
}

if ([response.StatusCode intValue] != 200) {
    NSLog(@"%@%d",@"HTTP status: ",[response.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[response GetHeaderField: @"x-ms-request-id"]);
    //  Do not print full response bodies, tokens, or diagnostic logs.
    NSLog(@"%@",@"Request failed. Inspect private diagnostics; reconcile writes before retrying.");
    return;
}

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

[stringCompare SetString: [result StringOf: @"access_token"]];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || (stringMatch4 == YES)) {
    NSLog(@"%@",@"Missing or invalid access_token.");
    return;
}

[stringCompare SetString: [result StringOf: @"token_type"]];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"Bearer" caseSensitive: YES];
if (stringMatch5 != YES) {
    NSLog(@"%@",@"Expected a Bearer token.");
    return;
}

if ([[result JsonTypeOf: @"expires_in"] intValue] != 2) {
    NSLog(@"%@",@"Missing numeric token lifetime.");
    return;
}

NSString *lifetime = [result StringOf: @"expires_in"];
CkoStringBuilder *validate5 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet5 = [[CkoStringBuilder alloc] init];
success = [validate5 Append: lifetime];
if (success != YES) {
    NSLog(@"%@",@"Could not validate expires_in.");
    return;
}

success = [alphabet5 Append: @"0123456789"];
if (success != YES) {
    NSLog(@"%@",@"Could not initialize validation.");
    return;
}

if (([validate5.Length intValue] < 1) || ([validate5.Length intValue] > 8)) {
    NSLog(@"%@",@"Invalid expires_in 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 expires_in.");
        return;
    }

    charIndex5 = charIndex5 + 1;
}

int seconds = [[result IntOf: @"expires_in"] intValue];
if ((seconds <= 60) || (seconds > 604800)) {
    NSLog(@"%@",@"Unexpected token lifetime.");
    return;
}

success = [expires AddSeconds: [NSNumber numberWithInt: seconds]];
if (success != YES) {
    NSLog(@"%@",@"Could not compute expiration.");
    return;
}

CkoDateTime *now = [[CkoDateTime alloc] init];
success = [now SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read current time.");
    return;
}

if ([[expires DiffSeconds: now] intValue] <= 60) {
    NSLog(@"%@",@"Token is expired or near expiration. Obtain a new token before continuing.");
    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: [expires 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 token to the private token file.");
    return;
}

NSLog(@"%@",@"Access token saved privately. No refresh token is issued for client credentials.");