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

Azure Key Vault: Cache Tokens and Retry a Read with Backoff

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.

A single-caller example using client_id, client_secret, tenant_id, vault_name and cert_name. Reuses a valid private token cache only for the configured tenant/client and Key Vault resource, renews near expiry, and allows one token renewal after 401. The certificate GET gets at most five attempts. Honors numeric or HTTP-date Retry-After, adds jitter, and stops rather than shortening waits above 30 seconds. Retries only selected transient HTTP statuses; transport failures stop. Does not replay mutations or retry rejected token requests. Protect/cache tokens per identity and tenant; concurrent applications need synchronization and atomic cache replacement.

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 <CkoPrng.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: @"vault_name"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"vault_name"] intValue] != 1) || (stringMatch1 == YES)) {
    NSLog(@"%@",@"Missing or invalid vault_name.");
    return;
}

CkoStringBuilder *validate1 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet1 = [[CkoStringBuilder alloc] init];
success = [validate1 Append: [config StringOf: @"vault_name"]];
if (success != YES) {
    NSLog(@"%@",@"Could not validate vault_name.");
    return;
}

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

if (([validate1.Length intValue] < 3) || ([validate1.Length intValue] > 24)) {
    NSLog(@"%@",@"Invalid vault_name length.");
    return;
}

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

    charIndex1 = charIndex1 + 1;
}

CkoStringBuilder *vaultName = [[CkoStringBuilder alloc] init];
[vaultName Append: [config StringOf: @"vault_name"]];
CkoStringBuilder *letters = [[CkoStringBuilder alloc] init];
[letters Append: @"abcdefghijklmnopqrstuvwxyz"];
if (([letters Contains: [vaultName GetRange: [NSNumber numberWithInt: 0] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) || ([vaultName EndsWith: @"-" caseSensitive: YES] == YES) || ([vaultName Contains: @"--" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Invalid vault_name.");
    return;
}

CkoStringBuilder *origin = [[CkoStringBuilder alloc] init];
success = [origin Append: @"https://"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [origin Append: [config StringOf: @"vault_name"]];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [origin Append: @".vault.azure.net"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

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

CkoStringBuilder *validate2 = [[CkoStringBuilder alloc] init];
CkoStringBuilder *alphabet2 = [[CkoStringBuilder alloc] init];
success = [validate2 Append: [config StringOf: @"cert_name"]];
if (success != YES) {
    NSLog(@"%@",@"Could not validate cert_name.");
    return;
}

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

if (([validate2.Length intValue] < 1) || ([validate2.Length intValue] > 127)) {
    NSLog(@"%@",@"Invalid cert_name length.");
    return;
}

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

    charIndex2 = charIndex2 + 1;
}

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

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

[stringCompare SetString: [config StringOf: @"tenant_id"]];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[config JsonTypeOf: @"tenant_id"] intValue] != 1) || (stringMatch5 == 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 *readUrl = [[CkoStringBuilder alloc] init];
success = [readUrl Append: [origin GetAsString]];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [readUrl Append: @"/certificates/"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [readUrl Append: [config StringOf: @"cert_name"]];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [readUrl Append: @"?api-version=2026-04-01"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

CkoJsonObject *cache = [[CkoJsonObject alloc] init];
cache.Strict = YES;
CkoDateTime *expires = [[CkoDateTime alloc] init];
CkoDateTime *now = [[CkoDateTime alloc] init];
BOOL refresh = YES;
success = [cache LoadFile: @"qa_data/tokens/azureKeyVaultToken.json"];
if (success == YES) {
    [stringCompare SetString: [cache StringOf: @"tenant_id"]];
    BOOL stringMatch6 = [stringCompare ContentsEqual: [config StringOf: @"tenant_id"] caseSensitive: YES];
    [stringCompare SetString: [cache StringOf: @"client_id"]];
    BOOL stringMatch7 = [stringCompare ContentsEqual: [config StringOf: @"client_id"] caseSensitive: YES];
    [stringCompare SetString: [cache StringOf: @"resource"]];
    BOOL stringMatch8 = [stringCompare ContentsEqual: @"https://vault.azure.net" caseSensitive: YES];
    if (([[cache JsonTypeOf: @"access_token"] intValue] == 1) && ([[cache JsonTypeOf: @"expires_at"] intValue] == 1) && (stringMatch6 == YES) && (stringMatch7 == YES) && (stringMatch8 == YES)) {
        success = [expires SetFromTimestamp: [cache StringOf: @"expires_at"]];
        if (success == YES) {
            success = [now SetFromCurrentSystemTime];
            if (success != YES) {
                NSLog(@"%@",@"Could not read time.");
                return;
            }

            [stringCompare SetString: [cache StringOf: @"access_token"]];
            BOOL stringMatch9 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
            if (([[expires DiffSeconds: now] intValue] > 60) && (stringMatch9 != YES)) {
                http.AuthToken = [cache StringOf: @"access_token"];
                refresh = NO;
            }

        }

    }

}

CkoHttp *authHttp = [[CkoHttp alloc] init];
authHttp.RequireSslCertVerify = YES;
authHttp.FollowRedirects = NO;
authHttp.ConnectTimeout = [NSNumber numberWithInt:20];
authHttp.ReadTimeout = [NSNumber numberWithInt:60];
CkoHttpRequest *authRequest = [[CkoHttpRequest alloc] init];
authRequest.HttpVerb = @"POST";
authRequest.ContentType = @"application/x-www-form-urlencoded";
[authRequest AddParam: @"client_id" value: [config StringOf: @"client_id"]];
[authRequest AddParam: @"client_secret" value: [config StringOf: @"client_secret"]];
[authRequest AddParam: @"scope" value: @"https://vault.azure.net/.default"];
[authRequest AddParam: @"grant_type" value: @"client_credentials"];
CkoHttpResponse *authResponse = [[CkoHttpResponse alloc] init];
CkoJsonObject *authResult = [[CkoJsonObject alloc] init];
authResult.Strict = YES;
CkoStringBuilder *authUrl = [[CkoStringBuilder alloc] init];
success = [authUrl Append: @"https://login.microsoftonline.com/"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [authUrl Append: [config StringOf: @"tenant_id"]];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

success = [authUrl Append: @"/oauth2/v2.0/token"];
if (success != YES) {
    NSLog(@"%@",@"Could not construct URL or identifier.");
    return;
}

int attempt = 0;
int delaySeconds = 1;
BOOL retried401 = NO;
BOOL complete = NO;
CkoPrng *jitter = [[CkoPrng alloc] init];
while (((attempt < 5) && (complete != YES))) {
    attempt = attempt + 1;
    success = [now SetFromCurrentSystemTime];
    if (success != YES) {
        NSLog(@"%@",@"Could not read time.");
        return;
    }

    if (refresh != YES) {
        if ([[expires DiffSeconds: now] intValue] <= 60) {
            refresh = YES;
        }

    }

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

        success = [authHttp HttpReq: [authUrl GetAsString] request: authRequest response: authResponse];
        if (success != YES) {
            NSLog(@"%@",@"Token request failed.");
            return;
        }

        if ([authResponse.StatusCode intValue] != 200) {
            NSLog(@"%@",@"Token request was rejected; no blind authentication retries.");
            return;
        }

        success = [authResult Load: authResponse.BodyStr];
        if (success != YES) {
            NSLog(@"%@",@"Invalid token response.");
            return;
        }

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

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

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

        CkoStringBuilder *validate9 = [[CkoStringBuilder alloc] init];
        CkoStringBuilder *alphabet9 = [[CkoStringBuilder alloc] init];
        success = [validate9 Append: [authResult StringOf: @"expires_in"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not validate token lifetime.");
            return;
        }

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

        if (([validate9.Length intValue] < 1) || ([validate9.Length intValue] > 8)) {
            NSLog(@"%@",@"Invalid token lifetime length.");
            return;
        }

        int charIndex9 = 0;
        while ((charIndex9 < [validate9.Length intValue])) {
            if ([alphabet9 Contains: [validate9 GetRange: [NSNumber numberWithInt: charIndex9] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
                NSLog(@"%@",@"Invalid character in token lifetime.");
                return;
            }

            charIndex9 = charIndex9 + 1;
        }

        int tokenLifetime = [[authResult 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: [authResult 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 UpdateString: @"tenant_id" value: [config StringOf: @"tenant_id"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not set tenant_id.");
            return;
        }

        success = [saved UpdateString: @"client_id" value: [config StringOf: @"client_id"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not set client_id.");
            return;
        }

        success = [saved UpdateString: @"resource" value: @"https://vault.azure.net"];
        if (success != YES) {
            NSLog(@"%@",@"Could not set resource.");
            return;
        }

        success = [saved WriteFile: @"qa_data/tokens/azureKeyVaultToken.json"];
        if (success != YES) {
            NSLog(@"%@",@"Could not save the private token file.");
            return;
        }

        success = [expires SetFromTimestamp: [saved StringOf: @"expires_at"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not read cached expiry.");
            return;
        }

        http.AuthToken = [saved StringOf: @"access_token"];
        refresh = NO;
    }

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

    if ([response.StatusCode intValue] == 200) {
        success = [result Load: response.BodyStr];
        if (success != YES) {
            NSLog(@"%@",@"Invalid certificate response.");
            return;
        }

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

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

        complete = YES;
    }
    else {
        if (([response.StatusCode intValue] == 401) && (retried401 != YES)) {
            refresh = YES;
            retried401 = YES;
        }
        else {
            if (([response.StatusCode intValue] != 429) && ([response.StatusCode intValue] != 500) && ([response.StatusCode intValue] != 502) && ([response.StatusCode intValue] != 503) && ([response.StatusCode intValue] != 504)) {
                NSLog(@"%@",@"Non-retryable status or repeated 401.");
                return;
            }

            if (attempt == 5) {
                NSLog(@"%@",@"Read retry limit reached.");
                return;
            }

            int waitSeconds = delaySeconds;
            NSString *retryAfter = [response GetHeaderField: @"Retry-After"];
            [stringCompare SetString: retryAfter];
            BOOL stringMatch14 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
            if (stringMatch14 != YES) {
                CkoStringBuilder *retryText = [[CkoStringBuilder alloc] init];
                [retryText Append: retryAfter];
                BOOL numeric = YES;
                CkoStringBuilder *digits = [[CkoStringBuilder alloc] init];
                [digits Append: @"0123456789"];
                int index = 0;
                while ((index < [retryText.Length intValue])) {
                    if ([digits Contains: [retryText GetRange: [NSNumber numberWithInt: index] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
                        numeric = NO;
                    }

                    index = index + 1;
                }

                if (numeric == YES) {
                    if ([retryText.Length intValue] > 8) {
                        NSLog(@"%@",@"Retry-After exceeds this example budget; retry later.");
                        return;
                    }

                    waitSeconds = [retryText.IntValue intValue];
                }
                else {
                    CkoDateTime *retryDate = [[CkoDateTime alloc] init];
                    success = [retryDate SetFromRfc822: retryAfter];
                    if (success != YES) {
                        NSLog(@"%@",@"Invalid Retry-After date.");
                        return;
                    }

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

                    waitSeconds = [[retryDate DiffSeconds: now] intValue];
                }

            }

            if (waitSeconds < 0) {
                waitSeconds = 0;
            }

            if (waitSeconds > 30) {
                NSLog(@"%@",@"Retry-After exceeds this example budget; retry later without shortening it.");
                return;
            }

            int waitMs = waitSeconds * 1000 + [[jitter RandomInt: [NSNumber numberWithInt: 0] high: [NSNumber numberWithInt: 250]] intValue];
            [http SleepMs: [NSNumber numberWithInt: waitMs]];
            delaySeconds = delaySeconds * 2;
        }

    }

}

if (complete != YES) {
    NSLog(@"%@",@"Read did not complete within the attempt budget.");
    return;
}

NSLog(@"%@",@"Example completed.");