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.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Prng;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
StringBuilder stringCompare = new StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
JsonObject config = new JsonObject();
config.setStrict(true);
try {
config.loadFile("qa_data/azure/keyvault.json");
} catch (ChilkatException e) {
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)) {
System.out.println("Missing or invalid vault_name.");
return;
}
StringBuilder validate1 = new StringBuilder();
StringBuilder alphabet1 = new StringBuilder();
try {
validate1.append(config.stringOf("vault_name"));
} catch (ChilkatException e) {
System.out.println("Could not validate vault_name.");
return;
}
try {
alphabet1.append("abcdefghijklmnopqrstuvwxyz0123456789-");
} catch (ChilkatException e) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate1.getLength() < 3) || (validate1.getLength() > 24)) {
System.out.println("Invalid vault_name length.");
return;
}
int charIndex1 = 0;
while (charIndex1 < validate1.getLength()) {
if (!alphabet1.contains(validate1.getRange(charIndex1, 1, false), true)) {
System.out.println("Invalid character in vault_name.");
return;
}
charIndex1 = charIndex1 + 1;
}
StringBuilder vaultName = new StringBuilder();
vaultName.append(config.stringOf("vault_name"));
StringBuilder letters = new StringBuilder();
letters.append("abcdefghijklmnopqrstuvwxyz");
if ((!letters.contains(vaultName.getRange(0, 1, false), true)) || ((vaultName.endsWith("-", true)) || (vaultName.contains("--", true)))) {
System.out.println("Invalid vault_name.");
return;
}
StringBuilder origin = new StringBuilder();
try {
origin.append("https://");
origin.append(config.stringOf("vault_name"));
origin.append(".vault.azure.net");
} catch (ChilkatException e) {
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)) {
System.out.println("Missing or invalid cert_name.");
return;
}
StringBuilder validate2 = new StringBuilder();
StringBuilder alphabet2 = new StringBuilder();
try {
validate2.append(config.stringOf("cert_name"));
} catch (ChilkatException e) {
System.out.println("Could not validate cert_name.");
return;
}
try {
alphabet2.append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
} catch (ChilkatException e) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate2.getLength() < 1) || (validate2.getLength() > 127)) {
System.out.println("Invalid cert_name length.");
return;
}
int charIndex2 = 0;
while (charIndex2 < validate2.getLength()) {
if (!alphabet2.contains(validate2.getRange(charIndex2, 1, false), 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)) {
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)) {
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)) {
System.out.println("Missing or invalid tenant_id.");
return;
}
StringBuilder validate4 = new StringBuilder();
StringBuilder alphabet4 = new StringBuilder();
try {
validate4.append(config.stringOf("tenant_id"));
} catch (ChilkatException e) {
System.out.println("Could not validate tenant GUID.");
return;
}
try {
alphabet4.append("0123456789abcdefABCDEF-");
} catch (ChilkatException e) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate4.getLength() < 36) || (validate4.getLength() > 36)) {
System.out.println("Invalid tenant GUID length.");
return;
}
int charIndex4 = 0;
while (charIndex4 < validate4.getLength()) {
if (!alphabet4.contains(validate4.getRange(charIndex4, 1, false), true)) {
System.out.println("Invalid character in tenant GUID.");
return;
}
charIndex4 = charIndex4 + 1;
}
Http http = new Http();
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
http.setConnectTimeout(20);
http.setReadTimeout(60);
http.setVerboseLogging(false);
HttpRequest request = new HttpRequest();
request.setHttpVerb("GET");
HttpResponse response = new HttpResponse();
JsonObject result = new JsonObject();
result.setStrict(true);
StringBuilder readUrl = new StringBuilder();
try {
readUrl.append(origin.getAsString());
readUrl.append("/certificates/");
readUrl.append(config.stringOf("cert_name"));
readUrl.append("?api-version=2026-04-01");
} catch (ChilkatException e) {
System.out.println("Could not construct URL or identifier.");
return;
}
JsonObject cache = new JsonObject();
cache.setStrict(true);
DateTime expires = new DateTime();
DateTime now = new DateTime();
boolean refresh = true;
try {
cache.loadFile("qa_data/tokens/azureKeyVaultToken.json");
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
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) && ((stringMatch7) && (stringMatch8))))) {
try {
expires.setFromTimestamp(cache.stringOf("expires_at"));
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
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)) {
http.setAuthToken(cache.stringOf("access_token"));
refresh = false;
}
}
}
}
Http authHttp = new Http();
authHttp.setRequireSslCertVerify(true);
authHttp.setFollowRedirects(false);
authHttp.setConnectTimeout(20);
authHttp.setReadTimeout(60);
HttpRequest authRequest = new HttpRequest();
authRequest.setHttpVerb("POST");
authRequest.setContentType("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");
HttpResponse authResponse = new HttpResponse();
JsonObject authResult = new JsonObject();
authResult.setStrict(true);
StringBuilder authUrl = new StringBuilder();
try {
authUrl.append("https://login.microsoftonline.com/");
authUrl.append(config.stringOf("tenant_id"));
authUrl.append("/oauth2/v2.0/token");
} catch (ChilkatException e) {
System.out.println("Could not construct URL or identifier.");
return;
}
int attempt = 0;
int delaySeconds = 1;
boolean retried401 = false;
boolean complete = false;
Prng jitter = new Prng();
while ((attempt < 5) && (!complete)) {
attempt = attempt + 1;
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read time.");
return;
}
if (!refresh) {
if (expires.diffSeconds(now) <= 60) {
refresh = true;
}
}
if (refresh) {
DateTime tokenExpires = new DateTime();
try {
tokenExpires.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read time.");
return;
}
try {
authHttp.httpReq(authUrl.getAsString(), authRequest, authResponse);
} catch (ChilkatException e) {
System.out.println("Token request failed.");
return;
}
if (authResponse.getStatusCode() != 200) {
System.out.println("Token request was rejected; no blind authentication retries.");
return;
}
try {
authResult.load(authResponse.getBodyStr());
} catch (ChilkatException e) {
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)) {
System.out.println("Missing or invalid access_token.");
return;
}
stringCompare.setString(authResult.stringOf("token_type"));
boolean stringMatch11 = stringCompare.contentsEqual("Bearer", true);
if (!stringMatch11) {
System.out.println("Expected Bearer token.");
return;
}
if (authResult.jsonTypeOf("expires_in") != 2) {
System.out.println("Missing token lifetime.");
return;
}
StringBuilder validate9 = new StringBuilder();
StringBuilder alphabet9 = new StringBuilder();
try {
validate9.append(authResult.stringOf("expires_in"));
} catch (ChilkatException e) {
System.out.println("Could not validate token lifetime.");
return;
}
try {
alphabet9.append("0123456789");
} catch (ChilkatException e) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate9.getLength() < 1) || (validate9.getLength() > 8)) {
System.out.println("Invalid token lifetime length.");
return;
}
int charIndex9 = 0;
while (charIndex9 < validate9.getLength()) {
if (!alphabet9.contains(validate9.getRange(charIndex9, 1, false), 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;
}
try {
tokenExpires.addSeconds(tokenLifetime);
} catch (ChilkatException e) {
System.out.println("Could not calculate expiration.");
return;
}
DateTime tokenNow = new DateTime();
try {
tokenNow.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read time.");
return;
}
if (tokenExpires.diffSeconds(tokenNow) <= 60) {
System.out.println("Token expired before it could be saved.");
return;
}
JsonObject saved = new JsonObject();
try {
saved.updateString("access_token", authResult.stringOf("access_token"));
} catch (ChilkatException e) {
System.out.println("Could not set access_token.");
return;
}
try {
saved.updateString("expires_at", tokenExpires.getAsTimestamp(false));
} catch (ChilkatException e) {
System.out.println("Could not set expires_at.");
return;
}
try {
saved.updateString("tenant_id", config.stringOf("tenant_id"));
} catch (ChilkatException e) {
System.out.println("Could not set tenant_id.");
return;
}
try {
saved.updateString("client_id", config.stringOf("client_id"));
} catch (ChilkatException e) {
System.out.println("Could not set client_id.");
return;
}
try {
saved.updateString("resource", "https://vault.azure.net");
} catch (ChilkatException e) {
System.out.println("Could not set resource.");
return;
}
try {
saved.writeFile("qa_data/tokens/azureKeyVaultToken.json");
} catch (ChilkatException e) {
System.out.println("Could not save the private token file.");
return;
}
try {
expires.setFromTimestamp(saved.stringOf("expires_at"));
} catch (ChilkatException e) {
System.out.println("Could not read cached expiry.");
return;
}
http.setAuthToken(saved.stringOf("access_token"));
refresh = false;
}
try {
http.httpReq(readUrl.getAsString(), request, response);
} catch (ChilkatException e) {
System.out.println("Read transport failed; inspect diagnostics privately.");
return;
}
if (response.getStatusCode() == 200) {
try {
result.load(response.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Invalid certificate response.");
return;
}
stringCompare.setString(result.stringOf("id"));
boolean stringMatch12 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("id") != 1) || (stringMatch12)) {
System.out.println("Missing or invalid id.");
return;
}
stringCompare.setString(result.stringOf("cer"));
boolean stringMatch13 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("cer") != 1) || (stringMatch13)) {
System.out.println("Missing or invalid cer.");
return;
}
complete = true;
} else {
if ((response.getStatusCode() == 401) && (!retried401)) {
refresh = true;
retried401 = true;
} else {
if ((response.getStatusCode() != 429) && ((response.getStatusCode() != 500) && ((response.getStatusCode() != 502) && ((response.getStatusCode() != 503) && (response.getStatusCode() != 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) {
StringBuilder retryText = new StringBuilder();
retryText.append(retryAfter);
boolean numeric = true;
StringBuilder digits = new StringBuilder();
digits.append("0123456789");
int index = 0;
while (index < retryText.getLength()) {
if (!digits.contains(retryText.getRange(index, 1, false), true)) {
numeric = false;
}
index = index + 1;
}
if (numeric) {
if (retryText.getLength() > 8) {
System.out.println("Retry-After exceeds this example budget; retry later.");
return;
}
waitSeconds = retryText.getIntValue();
} else {
DateTime retryDate = new DateTime();
try {
retryDate.setFromRfc822(retryAfter);
} catch (ChilkatException e) {
System.out.println("Invalid Retry-After date.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
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) {
System.out.println("Read did not complete within the attempt budget.");
return;
}
System.out.println("Example completed.");
}
}