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

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

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

    stringCompare.SetString(config.stringOf("vault_name"));
    boolean stringMatch1 = stringCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("vault_name") != 1) || (stringMatch1 == true)) {
        System.out.println("Missing or invalid vault_name.");
        return;
        }

    CkStringBuilder validate1 = new CkStringBuilder();
    CkStringBuilder alphabet1 = new CkStringBuilder();
    success = validate1.Append(config.stringOf("vault_name"));
    if (success != true) {
        System.out.println("Could not validate vault_name.");
        return;
        }

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

    if ((validate1.get_Length() < 3) || (validate1.get_Length() > 24)) {
        System.out.println("Invalid vault_name length.");
        return;
        }

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

        charIndex1 = charIndex1+1;
        }

    CkStringBuilder vaultName = new CkStringBuilder();
    vaultName.Append(config.stringOf("vault_name"));
    CkStringBuilder letters = new CkStringBuilder();
    letters.Append("abcdefghijklmnopqrstuvwxyz");
    if ((letters.Contains(vaultName.getRange(0,1,false),true) != true) || (vaultName.EndsWith("-",true) == true) || (vaultName.Contains("--",true) == true)) {
        System.out.println("Invalid vault_name.");
        return;
        }

    CkStringBuilder origin = new CkStringBuilder();
    success = origin.Append("https://");
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

    success = origin.Append(config.stringOf("vault_name"));
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

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

    stringCompare.SetString(config.stringOf("cert_name"));
    boolean stringMatch2 = stringCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("cert_name") != 1) || (stringMatch2 == true)) {
        System.out.println("Missing or invalid cert_name.");
        return;
        }

    CkStringBuilder validate2 = new CkStringBuilder();
    CkStringBuilder alphabet2 = new CkStringBuilder();
    success = validate2.Append(config.stringOf("cert_name"));
    if (success != true) {
        System.out.println("Could not validate cert_name.");
        return;
        }

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

    if ((validate2.get_Length() < 1) || (validate2.get_Length() > 127)) {
        System.out.println("Invalid cert_name length.");
        return;
        }

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

        charIndex2 = charIndex2+1;
        }

    stringCompare.SetString(config.stringOf("client_id"));
    boolean stringMatch3 = stringCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("client_id") != 1) || (stringMatch3 == true)) {
        System.out.println("Missing or invalid client_id.");
        return;
        }

    stringCompare.SetString(config.stringOf("client_secret"));
    boolean stringMatch4 = stringCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("client_secret") != 1) || (stringMatch4 == true)) {
        System.out.println("Missing or invalid client_secret.");
        return;
        }

    stringCompare.SetString(config.stringOf("tenant_id"));
    boolean stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((config.JsonTypeOf("tenant_id") != 1) || (stringMatch5 == true)) {
        System.out.println("Missing or invalid tenant_id.");
        return;
        }

    CkStringBuilder validate4 = new CkStringBuilder();
    CkStringBuilder alphabet4 = new CkStringBuilder();
    success = validate4.Append(config.stringOf("tenant_id"));
    if (success != true) {
        System.out.println("Could not validate tenant GUID.");
        return;
        }

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

    if ((validate4.get_Length() < 36) || (validate4.get_Length() > 36)) {
        System.out.println("Invalid tenant GUID length.");
        return;
        }

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

        charIndex4 = charIndex4+1;
        }

    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    http.put_VerboseLogging(false);
    CkHttpRequest request = new CkHttpRequest();
    request.put_HttpVerb("GET");
    CkHttpResponse response = new CkHttpResponse();
    CkJsonObject result = new CkJsonObject();
    result.put_Strict(true);
    CkStringBuilder readUrl = new CkStringBuilder();
    success = readUrl.Append(origin.getAsString());
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

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

    success = readUrl.Append(config.stringOf("cert_name"));
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

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

    CkJsonObject cache = new CkJsonObject();
    cache.put_Strict(true);
    CkDateTime expires = new CkDateTime();
    CkDateTime now = new CkDateTime();
    boolean refresh = true;
    success = cache.LoadFile("qa_data/tokens/azureKeyVaultToken.json");
    if (success == true) {
        stringCompare.SetString(cache.stringOf("tenant_id"));
        boolean stringMatch6 = stringCompare.ContentsEqual(config.stringOf("tenant_id"),true);
        stringCompare.SetString(cache.stringOf("client_id"));
        boolean stringMatch7 = stringCompare.ContentsEqual(config.stringOf("client_id"),true);
        stringCompare.SetString(cache.stringOf("resource"));
        boolean 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) {
                    System.out.println("Could not read time.");
                    return;
                    }

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

                }

            }

        }

    CkHttp authHttp = new CkHttp();
    authHttp.put_RequireSslCertVerify(true);
    authHttp.put_FollowRedirects(false);
    authHttp.put_ConnectTimeout(20);
    authHttp.put_ReadTimeout(60);
    CkHttpRequest authRequest = new CkHttpRequest();
    authRequest.put_HttpVerb("POST");
    authRequest.put_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");
    CkHttpResponse authResponse = new CkHttpResponse();
    CkJsonObject authResult = new CkJsonObject();
    authResult.put_Strict(true);
    CkStringBuilder authUrl = new CkStringBuilder();
    success = authUrl.Append("https://login.microsoftonline.com/");
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

    success = authUrl.Append(config.stringOf("tenant_id"));
    if (success != true) {
        System.out.println("Could not construct URL or identifier.");
        return;
        }

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

    int attempt = 0;
    int delaySeconds = 1;
    boolean retried401 = false;
    boolean complete = false;
    CkPrng jitter = new CkPrng();
    while (((attempt < 5) && (complete != true))) {
        attempt = attempt+1;
        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            System.out.println("Could not read time.");
            return;
            }

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

            }

        if (refresh == true) {
            CkDateTime tokenExpires = new CkDateTime();
            success = tokenExpires.SetFromCurrentSystemTime();
            if (success != true) {
                System.out.println("Could not read time.");
                return;
                }

            success = authHttp.HttpReq(authUrl.getAsString(),authRequest,authResponse);
            if (success != true) {
                System.out.println("Token request failed.");
                return;
                }

            if (authResponse.get_StatusCode() != 200) {
                System.out.println("Token request was rejected; no blind authentication retries.");
                return;
                }

            success = authResult.Load(authResponse.bodyStr());
            if (success != true) {
                System.out.println("Invalid token response.");
                return;
                }

            stringCompare.SetString(authResult.stringOf("access_token"));
            boolean stringMatch10 = stringCompare.ContentsEqual("",true);
            if ((authResult.JsonTypeOf("access_token") != 1) || (stringMatch10 == true)) {
                System.out.println("Missing or invalid access_token.");
                return;
                }

            stringCompare.SetString(authResult.stringOf("token_type"));
            boolean stringMatch11 = stringCompare.ContentsEqual("Bearer",true);
            if (stringMatch11 != true) {
                System.out.println("Expected Bearer token.");
                return;
                }

            if ((authResult.JsonTypeOf("expires_in") != 2)) {
                System.out.println("Missing token lifetime.");
                return;
                }

            CkStringBuilder validate9 = new CkStringBuilder();
            CkStringBuilder alphabet9 = new CkStringBuilder();
            success = validate9.Append(authResult.stringOf("expires_in"));
            if (success != true) {
                System.out.println("Could not validate token lifetime.");
                return;
                }

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

            if ((validate9.get_Length() < 1) || (validate9.get_Length() > 8)) {
                System.out.println("Invalid token lifetime length.");
                return;
                }

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

                charIndex9 = charIndex9+1;
                }

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

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

            CkDateTime tokenNow = new CkDateTime();
            success = tokenNow.SetFromCurrentSystemTime();
            if (success != true) {
                System.out.println("Could not read time.");
                return;
                }

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

            CkJsonObject saved = new CkJsonObject();
            success = saved.UpdateString("access_token",authResult.stringOf("access_token"));
            if (success != true) {
                System.out.println("Could not set access_token.");
                return;
                }

            success = saved.UpdateString("expires_at",tokenExpires.getAsTimestamp(false));
            if (success != true) {
                System.out.println("Could not set expires_at.");
                return;
                }

            success = saved.UpdateString("tenant_id",config.stringOf("tenant_id"));
            if (success != true) {
                System.out.println("Could not set tenant_id.");
                return;
                }

            success = saved.UpdateString("client_id",config.stringOf("client_id"));
            if (success != true) {
                System.out.println("Could not set client_id.");
                return;
                }

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

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

            success = expires.SetFromTimestamp(saved.stringOf("expires_at"));
            if (success != true) {
                System.out.println("Could not read cached expiry.");
                return;
                }

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

        success = http.HttpReq(readUrl.getAsString(),request,response);
        if (success != true) {
            System.out.println("Read transport failed; inspect diagnostics privately.");
            return;
            }

        if (response.get_StatusCode() == 200) {
            success = result.Load(response.bodyStr());
            if (success != true) {
                System.out.println("Invalid certificate response.");
                return;
                }

            stringCompare.SetString(result.stringOf("id"));
            boolean stringMatch12 = stringCompare.ContentsEqual("",true);
            if ((result.JsonTypeOf("id") != 1) || (stringMatch12 == true)) {
                System.out.println("Missing or invalid id.");
                return;
                }

            stringCompare.SetString(result.stringOf("cer"));
            boolean stringMatch13 = stringCompare.ContentsEqual("",true);
            if ((result.JsonTypeOf("cer") != 1) || (stringMatch13 == true)) {
                System.out.println("Missing or invalid cer.");
                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)) {
                    System.out.println("Non-retryable status or repeated 401.");
                    return;
                    }

                if (attempt == 5) {
                    System.out.println("Read retry limit reached.");
                    return;
                    }

                int waitSeconds = delaySeconds;
                String retryAfter = response.getHeaderField("Retry-After");
                stringCompare.SetString(retryAfter);
                boolean stringMatch14 = stringCompare.ContentsEqual("",true);
                if (stringMatch14 != true) {
                    CkStringBuilder retryText = new CkStringBuilder();
                    retryText.Append(retryAfter);
                    boolean numeric = true;
                    CkStringBuilder digits = new CkStringBuilder();
                    digits.Append("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) {
                            System.out.println("Retry-After exceeds this example budget; retry later.");
                            return;
                            }

                        waitSeconds = retryText.get_IntValue();
                        }
                    else {
                        CkDateTime retryDate = new CkDateTime();
                        success = retryDate.SetFromRfc822(retryAfter);
                        if (success != true) {
                            System.out.println("Invalid Retry-After date.");
                            return;
                            }

                        success = now.SetFromCurrentSystemTime();
                        if (success != true) {
                            System.out.println("Could not read time.");
                            return;
                            }

                        waitSeconds = retryDate.DiffSeconds(now);
                        }

                    }

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

                if (waitSeconds > 30) {
                    System.out.println("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) {
        System.out.println("Read did not complete within the attempt budget.");
        return;
        }

    System.out.println("Example completed.");
  }
}