Sample code for 30+ languages & platforms
Unicode 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 Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkDateTimeW.h>
#include <CkPrngW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this configuration private, outside public web content and source control.
    CkJsonObjectW config;
    config.put_Strict(true);
    success = config.LoadFile(L"qa_data/azure/keyvault.json");
    if (success != true) {
        wprintf(L"Could not load private Key Vault configuration.\n");
        return;
    }

    stringCompare.SetString(config.stringOf(L"vault_name"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"vault_name") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid vault_name.\n");
        return;
    }

    CkStringBuilderW validate1;
    CkStringBuilderW alphabet1;
    success = validate1.Append(config.stringOf(L"vault_name"));
    if (success != true) {
        wprintf(L"Could not validate vault_name.\n");
        return;
    }

    success = alphabet1.Append(L"abcdefghijklmnopqrstuvwxyz0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate1.get_Length() < 3) || (validate1.get_Length() > 24)) {
        wprintf(L"Invalid vault_name length.\n");
        return;
    }

    int charIndex1 = 0;
    while ((charIndex1 < validate1.get_Length())) {
        if (alphabet1.Contains(validate1.getRange(charIndex1,1,false),true) != true) {
            wprintf(L"Invalid character in vault_name.\n");
            return;
        }

        charIndex1 = charIndex1 + 1;
    }

    CkStringBuilderW vaultName;
    vaultName.Append(config.stringOf(L"vault_name"));
    CkStringBuilderW letters;
    letters.Append(L"abcdefghijklmnopqrstuvwxyz");
    if ((letters.Contains(vaultName.getRange(0,1,false),true) != true) || (vaultName.EndsWith(L"-",true) == true) || (vaultName.Contains(L"--",true) == true)) {
        wprintf(L"Invalid vault_name.\n");
        return;
    }

    CkStringBuilderW origin;
    success = origin.Append(L"https://");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = origin.Append(config.stringOf(L"vault_name"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = origin.Append(L".vault.azure.net");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    stringCompare.SetString(config.stringOf(L"cert_name"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"cert_name") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid cert_name.\n");
        return;
    }

    CkStringBuilderW validate2;
    CkStringBuilderW alphabet2;
    success = validate2.Append(config.stringOf(L"cert_name"));
    if (success != true) {
        wprintf(L"Could not validate cert_name.\n");
        return;
    }

    success = alphabet2.Append(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate2.get_Length() < 1) || (validate2.get_Length() > 127)) {
        wprintf(L"Invalid cert_name length.\n");
        return;
    }

    int charIndex2 = 0;
    while ((charIndex2 < validate2.get_Length())) {
        if (alphabet2.Contains(validate2.getRange(charIndex2,1,false),true) != true) {
            wprintf(L"Invalid character in cert_name.\n");
            return;
        }

        charIndex2 = charIndex2 + 1;
    }

    stringCompare.SetString(config.stringOf(L"client_id"));
    bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"client_id") != 1) || (stringMatch3 == true)) {
        wprintf(L"Missing or invalid client_id.\n");
        return;
    }

    stringCompare.SetString(config.stringOf(L"client_secret"));
    bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"client_secret") != 1) || (stringMatch4 == true)) {
        wprintf(L"Missing or invalid client_secret.\n");
        return;
    }

    stringCompare.SetString(config.stringOf(L"tenant_id"));
    bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
    if ((config.JsonTypeOf(L"tenant_id") != 1) || (stringMatch5 == true)) {
        wprintf(L"Missing or invalid tenant_id.\n");
        return;
    }

    CkStringBuilderW validate4;
    CkStringBuilderW alphabet4;
    success = validate4.Append(config.stringOf(L"tenant_id"));
    if (success != true) {
        wprintf(L"Could not validate tenant GUID.\n");
        return;
    }

    success = alphabet4.Append(L"0123456789abcdefABCDEF-");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate4.get_Length() < 36) || (validate4.get_Length() > 36)) {
        wprintf(L"Invalid tenant GUID length.\n");
        return;
    }

    int charIndex4 = 0;
    while ((charIndex4 < validate4.get_Length())) {
        if (alphabet4.Contains(validate4.getRange(charIndex4,1,false),true) != true) {
            wprintf(L"Invalid character in tenant GUID.\n");
            return;
        }

        charIndex4 = charIndex4 + 1;
    }

    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    http.put_VerboseLogging(false);
    CkHttpRequestW request;
    request.put_HttpVerb(L"GET");
    CkHttpResponseW response;
    CkJsonObjectW result;
    result.put_Strict(true);
    CkStringBuilderW readUrl;
    success = readUrl.Append(origin.getAsString());
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = readUrl.Append(L"/certificates/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = readUrl.Append(config.stringOf(L"cert_name"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = readUrl.Append(L"?api-version=2026-04-01");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    CkJsonObjectW cache;
    cache.put_Strict(true);
    CkDateTimeW expires;
    CkDateTimeW now;
    bool refresh = true;
    success = cache.LoadFile(L"qa_data/tokens/azureKeyVaultToken.json");
    if (success == true) {
        stringCompare.SetString(cache.stringOf(L"tenant_id"));
        bool stringMatch6 = stringCompare.ContentsEqual(config.stringOf(L"tenant_id"),true);
        stringCompare.SetString(cache.stringOf(L"client_id"));
        bool stringMatch7 = stringCompare.ContentsEqual(config.stringOf(L"client_id"),true);
        stringCompare.SetString(cache.stringOf(L"resource"));
        bool stringMatch8 = stringCompare.ContentsEqual(L"https://vault.azure.net",true);
        if ((cache.JsonTypeOf(L"access_token") == 1) && (cache.JsonTypeOf(L"expires_at") == 1) && (stringMatch6 == true) && (stringMatch7 == true) && (stringMatch8 == true)) {
            success = expires.SetFromTimestamp(cache.stringOf(L"expires_at"));
            if (success == true) {
                success = now.SetFromCurrentSystemTime();
                if (success != true) {
                    wprintf(L"Could not read time.\n");
                    return;
                }

                stringCompare.SetString(cache.stringOf(L"access_token"));
                bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
                if ((expires.DiffSeconds(now) > 60) && (stringMatch9 != true)) {
                    http.put_AuthToken(cache.stringOf(L"access_token"));
                    refresh = false;
                }

            }

        }

    }

    CkHttpW authHttp;
    authHttp.put_RequireSslCertVerify(true);
    authHttp.put_FollowRedirects(false);
    authHttp.put_ConnectTimeout(20);
    authHttp.put_ReadTimeout(60);
    CkHttpRequestW authRequest;
    authRequest.put_HttpVerb(L"POST");
    authRequest.put_ContentType(L"application/x-www-form-urlencoded");
    authRequest.AddParam(L"client_id",config.stringOf(L"client_id"));
    authRequest.AddParam(L"client_secret",config.stringOf(L"client_secret"));
    authRequest.AddParam(L"scope",L"https://vault.azure.net/.default");
    authRequest.AddParam(L"grant_type",L"client_credentials");
    CkHttpResponseW authResponse;
    CkJsonObjectW authResult;
    authResult.put_Strict(true);
    CkStringBuilderW authUrl;
    success = authUrl.Append(L"https://login.microsoftonline.com/");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = authUrl.Append(config.stringOf(L"tenant_id"));
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    success = authUrl.Append(L"/oauth2/v2.0/token");
    if (success != true) {
        wprintf(L"Could not construct URL or identifier.\n");
        return;
    }

    int attempt = 0;
    int delaySeconds = 1;
    bool retried401 = false;
    bool complete = false;
    CkPrngW jitter;
    while (((attempt < 5) && (complete != true))) {
        attempt = attempt + 1;
        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            wprintf(L"Could not read time.\n");
            return;
        }

        if (refresh != true) {
            if (expires.DiffSeconds(now) <= 60) {
                refresh = true;
            }

        }

        if (refresh == true) {
            CkDateTimeW tokenExpires;
            success = tokenExpires.SetFromCurrentSystemTime();
            if (success != true) {
                wprintf(L"Could not read time.\n");
                return;
            }

            success = authHttp.HttpReq(authUrl.getAsString(),authRequest,authResponse);
            if (success != true) {
                wprintf(L"Token request failed.\n");
                return;
            }

            if (authResponse.get_StatusCode() != 200) {
                wprintf(L"Token request was rejected; no blind authentication retries.\n");
                return;
            }

            success = authResult.Load(authResponse.bodyStr());
            if (success != true) {
                wprintf(L"Invalid token response.\n");
                return;
            }

            stringCompare.SetString(authResult.stringOf(L"access_token"));
            bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
            if ((authResult.JsonTypeOf(L"access_token") != 1) || (stringMatch10 == true)) {
                wprintf(L"Missing or invalid access_token.\n");
                return;
            }

            stringCompare.SetString(authResult.stringOf(L"token_type"));
            bool stringMatch11 = stringCompare.ContentsEqual(L"Bearer",true);
            if (stringMatch11 != true) {
                wprintf(L"Expected Bearer token.\n");
                return;
            }

            if ((authResult.JsonTypeOf(L"expires_in") != 2)) {
                wprintf(L"Missing token lifetime.\n");
                return;
            }

            CkStringBuilderW validate9;
            CkStringBuilderW alphabet9;
            success = validate9.Append(authResult.stringOf(L"expires_in"));
            if (success != true) {
                wprintf(L"Could not validate token lifetime.\n");
                return;
            }

            success = alphabet9.Append(L"0123456789");
            if (success != true) {
                wprintf(L"Could not initialize validation.\n");
                return;
            }

            if ((validate9.get_Length() < 1) || (validate9.get_Length() > 8)) {
                wprintf(L"Invalid token lifetime length.\n");
                return;
            }

            int charIndex9 = 0;
            while ((charIndex9 < validate9.get_Length())) {
                if (alphabet9.Contains(validate9.getRange(charIndex9,1,false),true) != true) {
                    wprintf(L"Invalid character in token lifetime.\n");
                    return;
                }

                charIndex9 = charIndex9 + 1;
            }

            int tokenLifetime = authResult.IntOf(L"expires_in");
            if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
                wprintf(L"Unexpected token lifetime.\n");
                return;
            }

            success = tokenExpires.AddSeconds(tokenLifetime);
            if (success != true) {
                wprintf(L"Could not calculate expiration.\n");
                return;
            }

            CkDateTimeW tokenNow;
            success = tokenNow.SetFromCurrentSystemTime();
            if (success != true) {
                wprintf(L"Could not read time.\n");
                return;
            }

            if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
                wprintf(L"Token expired before it could be saved.\n");
                return;
            }

            CkJsonObjectW saved;
            success = saved.UpdateString(L"access_token",authResult.stringOf(L"access_token"));
            if (success != true) {
                wprintf(L"Could not set access_token.\n");
                return;
            }

            success = saved.UpdateString(L"expires_at",tokenExpires.getAsTimestamp(false));
            if (success != true) {
                wprintf(L"Could not set expires_at.\n");
                return;
            }

            success = saved.UpdateString(L"tenant_id",config.stringOf(L"tenant_id"));
            if (success != true) {
                wprintf(L"Could not set tenant_id.\n");
                return;
            }

            success = saved.UpdateString(L"client_id",config.stringOf(L"client_id"));
            if (success != true) {
                wprintf(L"Could not set client_id.\n");
                return;
            }

            success = saved.UpdateString(L"resource",L"https://vault.azure.net");
            if (success != true) {
                wprintf(L"Could not set resource.\n");
                return;
            }

            success = saved.WriteFile(L"qa_data/tokens/azureKeyVaultToken.json");
            if (success != true) {
                wprintf(L"Could not save the private token file.\n");
                return;
            }

            success = expires.SetFromTimestamp(saved.stringOf(L"expires_at"));
            if (success != true) {
                wprintf(L"Could not read cached expiry.\n");
                return;
            }

            http.put_AuthToken(saved.stringOf(L"access_token"));
            refresh = false;
        }

        success = http.HttpReq(readUrl.getAsString(),request,response);
        if (success != true) {
            wprintf(L"Read transport failed; inspect diagnostics privately.\n");
            return;
        }

        if (response.get_StatusCode() == 200) {
            success = result.Load(response.bodyStr());
            if (success != true) {
                wprintf(L"Invalid certificate response.\n");
                return;
            }

            stringCompare.SetString(result.stringOf(L"id"));
            bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
            if ((result.JsonTypeOf(L"id") != 1) || (stringMatch12 == true)) {
                wprintf(L"Missing or invalid id.\n");
                return;
            }

            stringCompare.SetString(result.stringOf(L"cer"));
            bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
            if ((result.JsonTypeOf(L"cer") != 1) || (stringMatch13 == true)) {
                wprintf(L"Missing or invalid cer.\n");
                return;
            }

            complete = true;
        }
        else {
            if ((response.get_StatusCode() == 401) && (retried401 != true)) {
                refresh = true;
                retried401 = true;
            }
            else {
                if ((response.get_StatusCode() != 429) && (response.get_StatusCode() != 500) && (response.get_StatusCode() != 502) && (response.get_StatusCode() != 503) && (response.get_StatusCode() != 504)) {
                    wprintf(L"Non-retryable status or repeated 401.\n");
                    return;
                }

                if (attempt == 5) {
                    wprintf(L"Read retry limit reached.\n");
                    return;
                }

                int waitSeconds = delaySeconds;
                const wchar_t *retryAfter = response.getHeaderField(L"Retry-After");
                stringCompare.SetString(retryAfter);
                bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
                if (stringMatch14 != true) {
                    CkStringBuilderW retryText;
                    retryText.Append(retryAfter);
                    bool numeric = true;
                    CkStringBuilderW digits;
                    digits.Append(L"0123456789");
                    int index = 0;
                    while ((index < retryText.get_Length())) {
                        if (digits.Contains(retryText.getRange(index,1,false),true) != true) {
                            numeric = false;
                        }

                        index = index + 1;
                    }

                    if (numeric == true) {
                        if (retryText.get_Length() > 8) {
                            wprintf(L"Retry-After exceeds this example budget; retry later.\n");
                            return;
                        }

                        waitSeconds = retryText.get_IntValue();
                    }
                    else {
                        CkDateTimeW retryDate;
                        success = retryDate.SetFromRfc822(retryAfter);
                        if (success != true) {
                            wprintf(L"Invalid Retry-After date.\n");
                            return;
                        }

                        success = now.SetFromCurrentSystemTime();
                        if (success != true) {
                            wprintf(L"Could not read time.\n");
                            return;
                        }

                        waitSeconds = retryDate.DiffSeconds(now);
                    }

                }

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

                if (waitSeconds > 30) {
                    wprintf(L"Retry-After exceeds this example budget; retry later without shortening it.\n");
                    return;
                }

                int waitMs = waitSeconds * 1000 + jitter.RandomInt(0,250);
                http.SleepMs(waitMs);
                delaySeconds = delaySeconds * 2;
            }

        }

    }

    if (complete != true) {
        wprintf(L"Read did not complete within the attempt budget.\n");
        return;
    }

    wprintf(L"Example completed.\n");
    }