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

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this configuration private, outside public web content and source control.
Chilkat.JsonObject config = new Chilkat.JsonObject();
config.Strict = true;
success = config.LoadFile("qa_data/azure/keyvault.json");
if (success != true) {
    Debug.WriteLine("Could not load private Key Vault configuration.");
    return;
}

stringCompare.SetString(config.StringOf("vault_name"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("vault_name") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid vault_name.");
    return;
}

Chilkat.StringBuilder validate1 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet1 = new Chilkat.StringBuilder();
success = validate1.Append(config.StringOf("vault_name"));
if (success != true) {
    Debug.WriteLine("Could not validate vault_name.");
    return;
}

success = alphabet1.Append("abcdefghijklmnopqrstuvwxyz0123456789-");
if (success != true) {
    Debug.WriteLine("Could not initialize validation.");
    return;
}

if ((validate1.Length < 3) || (validate1.Length > 24)) {
    Debug.WriteLine("Invalid vault_name length.");
    return;
}

int charIndex1 = 0;
while ((charIndex1 < validate1.Length)) {
    if (alphabet1.Contains(validate1.GetRange(charIndex1,1,false),true) != true) {
        Debug.WriteLine("Invalid character in vault_name.");
        return;
    }

    charIndex1 = charIndex1 + 1;
}

Chilkat.StringBuilder vaultName = new Chilkat.StringBuilder();
vaultName.Append(config.StringOf("vault_name"));
Chilkat.StringBuilder letters = new Chilkat.StringBuilder();
letters.Append("abcdefghijklmnopqrstuvwxyz");
if ((letters.Contains(vaultName.GetRange(0,1,false),true) != true) || (vaultName.EndsWith("-",true) == true) || (vaultName.Contains("--",true) == true)) {
    Debug.WriteLine("Invalid vault_name.");
    return;
}

Chilkat.StringBuilder origin = new Chilkat.StringBuilder();
success = origin.Append("https://");
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = origin.Append(config.StringOf("vault_name"));
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

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

stringCompare.SetString(config.StringOf("cert_name"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("cert_name") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid cert_name.");
    return;
}

Chilkat.StringBuilder validate2 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet2 = new Chilkat.StringBuilder();
success = validate2.Append(config.StringOf("cert_name"));
if (success != true) {
    Debug.WriteLine("Could not validate cert_name.");
    return;
}

success = alphabet2.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
if (success != true) {
    Debug.WriteLine("Could not initialize validation.");
    return;
}

if ((validate2.Length < 1) || (validate2.Length > 127)) {
    Debug.WriteLine("Invalid cert_name length.");
    return;
}

int charIndex2 = 0;
while ((charIndex2 < validate2.Length)) {
    if (alphabet2.Contains(validate2.GetRange(charIndex2,1,false),true) != true) {
        Debug.WriteLine("Invalid character in cert_name.");
        return;
    }

    charIndex2 = charIndex2 + 1;
}

stringCompare.SetString(config.StringOf("client_id"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("client_id") != 1) || (stringMatch3 == true)) {
    Debug.WriteLine("Missing or invalid client_id.");
    return;
}

stringCompare.SetString(config.StringOf("client_secret"));
bool stringMatch4 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("client_secret") != 1) || (stringMatch4 == true)) {
    Debug.WriteLine("Missing or invalid client_secret.");
    return;
}

stringCompare.SetString(config.StringOf("tenant_id"));
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("tenant_id") != 1) || (stringMatch5 == true)) {
    Debug.WriteLine("Missing or invalid tenant_id.");
    return;
}

Chilkat.StringBuilder validate4 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet4 = new Chilkat.StringBuilder();
success = validate4.Append(config.StringOf("tenant_id"));
if (success != true) {
    Debug.WriteLine("Could not validate tenant GUID.");
    return;
}

success = alphabet4.Append("0123456789abcdefABCDEF-");
if (success != true) {
    Debug.WriteLine("Could not initialize validation.");
    return;
}

if ((validate4.Length < 36) || (validate4.Length > 36)) {
    Debug.WriteLine("Invalid tenant GUID length.");
    return;
}

int charIndex4 = 0;
while ((charIndex4 < validate4.Length)) {
    if (alphabet4.Contains(validate4.GetRange(charIndex4,1,false),true) != true) {
        Debug.WriteLine("Invalid character in tenant GUID.");
        return;
    }

    charIndex4 = charIndex4 + 1;
}

Chilkat.Http http = new Chilkat.Http();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
http.ConnectTimeout = 20;
http.ReadTimeout = 60;
http.VerboseLogging = false;
Chilkat.HttpRequest request = new Chilkat.HttpRequest();
request.HttpVerb = "GET";
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
Chilkat.JsonObject result = new Chilkat.JsonObject();
result.Strict = true;
Chilkat.StringBuilder readUrl = new Chilkat.StringBuilder();
success = readUrl.Append(origin.GetAsString());
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = readUrl.Append("/certificates/");
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = readUrl.Append(config.StringOf("cert_name"));
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

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

Chilkat.JsonObject cache = new Chilkat.JsonObject();
cache.Strict = true;
Chilkat.CkDateTime expires = new Chilkat.CkDateTime();
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
bool refresh = true;
success = cache.LoadFile("qa_data/tokens/azureKeyVaultToken.json");
if (success == true) {
    stringCompare.SetString(cache.StringOf("tenant_id"));
    bool stringMatch6 = stringCompare.ContentsEqual(config.StringOf("tenant_id"),true);
    stringCompare.SetString(cache.StringOf("client_id"));
    bool stringMatch7 = stringCompare.ContentsEqual(config.StringOf("client_id"),true);
    stringCompare.SetString(cache.StringOf("resource"));
    bool stringMatch8 = stringCompare.ContentsEqual("https://vault.azure.net",true);
    if ((cache.JsonTypeOf("access_token") == 1) && (cache.JsonTypeOf("expires_at") == 1) && (stringMatch6 == true) && (stringMatch7 == true) && (stringMatch8 == true)) {
        success = expires.SetFromTimestamp(cache.StringOf("expires_at"));
        if (success == true) {
            success = now.SetFromCurrentSystemTime();
            if (success != true) {
                Debug.WriteLine("Could not read time.");
                return;
            }

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

        }

    }

}

Chilkat.Http authHttp = new Chilkat.Http();
authHttp.RequireSslCertVerify = true;
authHttp.FollowRedirects = false;
authHttp.ConnectTimeout = 20;
authHttp.ReadTimeout = 60;
Chilkat.HttpRequest authRequest = new Chilkat.HttpRequest();
authRequest.HttpVerb = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.AddParam("client_id",config.StringOf("client_id"));
authRequest.AddParam("client_secret",config.StringOf("client_secret"));
authRequest.AddParam("scope","https://vault.azure.net/.default");
authRequest.AddParam("grant_type","client_credentials");
Chilkat.HttpResponse authResponse = new Chilkat.HttpResponse();
Chilkat.JsonObject authResult = new Chilkat.JsonObject();
authResult.Strict = true;
Chilkat.StringBuilder authUrl = new Chilkat.StringBuilder();
success = authUrl.Append("https://login.microsoftonline.com/");
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = authUrl.Append(config.StringOf("tenant_id"));
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

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

int attempt = 0;
int delaySeconds = 1;
bool retried401 = false;
bool complete = false;
Chilkat.Prng jitter = new Chilkat.Prng();
while (((attempt < 5) && (complete != true))) {
    attempt = attempt + 1;
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Debug.WriteLine("Could not read time.");
        return;
    }

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

    }

    if (refresh == true) {
        Chilkat.CkDateTime tokenExpires = new Chilkat.CkDateTime();
        success = tokenExpires.SetFromCurrentSystemTime();
        if (success != true) {
            Debug.WriteLine("Could not read time.");
            return;
        }

        success = authHttp.HttpReq(authUrl.GetAsString(),authRequest,authResponse);
        if (success != true) {
            Debug.WriteLine("Token request failed.");
            return;
        }

        if (authResponse.StatusCode != 200) {
            Debug.WriteLine("Token request was rejected; no blind authentication retries.");
            return;
        }

        success = authResult.Load(authResponse.BodyStr);
        if (success != true) {
            Debug.WriteLine("Invalid token response.");
            return;
        }

        stringCompare.SetString(authResult.StringOf("access_token"));
        bool stringMatch10 = stringCompare.ContentsEqual("",true);
        if ((authResult.JsonTypeOf("access_token") != 1) || (stringMatch10 == true)) {
            Debug.WriteLine("Missing or invalid access_token.");
            return;
        }

        stringCompare.SetString(authResult.StringOf("token_type"));
        bool stringMatch11 = stringCompare.ContentsEqual("Bearer",true);
        if (stringMatch11 != true) {
            Debug.WriteLine("Expected Bearer token.");
            return;
        }

        if ((authResult.JsonTypeOf("expires_in") != 2)) {
            Debug.WriteLine("Missing token lifetime.");
            return;
        }

        Chilkat.StringBuilder validate9 = new Chilkat.StringBuilder();
        Chilkat.StringBuilder alphabet9 = new Chilkat.StringBuilder();
        success = validate9.Append(authResult.StringOf("expires_in"));
        if (success != true) {
            Debug.WriteLine("Could not validate token lifetime.");
            return;
        }

        success = alphabet9.Append("0123456789");
        if (success != true) {
            Debug.WriteLine("Could not initialize validation.");
            return;
        }

        if ((validate9.Length < 1) || (validate9.Length > 8)) {
            Debug.WriteLine("Invalid token lifetime length.");
            return;
        }

        int charIndex9 = 0;
        while ((charIndex9 < validate9.Length)) {
            if (alphabet9.Contains(validate9.GetRange(charIndex9,1,false),true) != true) {
                Debug.WriteLine("Invalid character in token lifetime.");
                return;
            }

            charIndex9 = charIndex9 + 1;
        }

        int tokenLifetime = authResult.IntOf("expires_in");
        if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
            Debug.WriteLine("Unexpected token lifetime.");
            return;
        }

        success = tokenExpires.AddSeconds(tokenLifetime);
        if (success != true) {
            Debug.WriteLine("Could not calculate expiration.");
            return;
        }

        Chilkat.CkDateTime tokenNow = new Chilkat.CkDateTime();
        success = tokenNow.SetFromCurrentSystemTime();
        if (success != true) {
            Debug.WriteLine("Could not read time.");
            return;
        }

        if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
            Debug.WriteLine("Token expired before it could be saved.");
            return;
        }

        Chilkat.JsonObject saved = new Chilkat.JsonObject();
        success = saved.UpdateString("access_token",authResult.StringOf("access_token"));
        if (success != true) {
            Debug.WriteLine("Could not set access_token.");
            return;
        }

        success = saved.UpdateString("expires_at",tokenExpires.GetAsTimestamp(false));
        if (success != true) {
            Debug.WriteLine("Could not set expires_at.");
            return;
        }

        success = saved.UpdateString("tenant_id",config.StringOf("tenant_id"));
        if (success != true) {
            Debug.WriteLine("Could not set tenant_id.");
            return;
        }

        success = saved.UpdateString("client_id",config.StringOf("client_id"));
        if (success != true) {
            Debug.WriteLine("Could not set client_id.");
            return;
        }

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

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

        success = expires.SetFromTimestamp(saved.StringOf("expires_at"));
        if (success != true) {
            Debug.WriteLine("Could not read cached expiry.");
            return;
        }

        http.AuthToken = saved.StringOf("access_token");
        refresh = false;
    }

    success = http.HttpReq(readUrl.GetAsString(),request,response);
    if (success != true) {
        Debug.WriteLine("Read transport failed; inspect diagnostics privately.");
        return;
    }

    if (response.StatusCode == 200) {
        success = result.Load(response.BodyStr);
        if (success != true) {
            Debug.WriteLine("Invalid certificate response.");
            return;
        }

        stringCompare.SetString(result.StringOf("id"));
        bool stringMatch12 = stringCompare.ContentsEqual("",true);
        if ((result.JsonTypeOf("id") != 1) || (stringMatch12 == true)) {
            Debug.WriteLine("Missing or invalid id.");
            return;
        }

        stringCompare.SetString(result.StringOf("cer"));
        bool stringMatch13 = stringCompare.ContentsEqual("",true);
        if ((result.JsonTypeOf("cer") != 1) || (stringMatch13 == true)) {
            Debug.WriteLine("Missing or invalid cer.");
            return;
        }

        complete = true;
    }
    else {
        if ((response.StatusCode == 401) && (retried401 != true)) {
            refresh = true;
            retried401 = true;
        }
        else {
            if ((response.StatusCode != 429) && (response.StatusCode != 500) && (response.StatusCode != 502) && (response.StatusCode != 503) && (response.StatusCode != 504)) {
                Debug.WriteLine("Non-retryable status or repeated 401.");
                return;
            }

            if (attempt == 5) {
                Debug.WriteLine("Read retry limit reached.");
                return;
            }

            int waitSeconds = delaySeconds;
            string retryAfter = response.GetHeaderField("Retry-After");
            stringCompare.SetString(retryAfter);
            bool stringMatch14 = stringCompare.ContentsEqual("",true);
            if (stringMatch14 != true) {
                Chilkat.StringBuilder retryText = new Chilkat.StringBuilder();
                retryText.Append(retryAfter);
                bool numeric = true;
                Chilkat.StringBuilder digits = new Chilkat.StringBuilder();
                digits.Append("0123456789");
                int index = 0;
                while ((index < retryText.Length)) {
                    if (digits.Contains(retryText.GetRange(index,1,false),true) != true) {
                        numeric = false;
                    }

                    index = index + 1;
                }

                if (numeric == true) {
                    if (retryText.Length > 8) {
                        Debug.WriteLine("Retry-After exceeds this example budget; retry later.");
                        return;
                    }

                    waitSeconds = retryText.IntValue;
                }
                else {
                    Chilkat.CkDateTime retryDate = new Chilkat.CkDateTime();
                    success = retryDate.SetFromRfc822(retryAfter);
                    if (success != true) {
                        Debug.WriteLine("Invalid Retry-After date.");
                        return;
                    }

                    success = now.SetFromCurrentSystemTime();
                    if (success != true) {
                        Debug.WriteLine("Could not read time.");
                        return;
                    }

                    waitSeconds = retryDate.DiffSeconds(now);
                }

            }

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

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

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

    }

}

if (complete != true) {
    Debug.WriteLine("Read did not complete within the attempt budget.");
    return;
}

Debug.WriteLine("Example completed.");