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 Ruby Downloads
require 'chilkat'
success = false
stringCompare = Chilkat::CkStringBuilder.new()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Keep this configuration private, outside public web content and source control.
config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("qa_data/azure/keyvault.json")
if (success != true)
print "Could not load private Key Vault configuration." + "\n";
exit
end
stringCompare.SetString(config.stringOf("vault_name"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("vault_name") != 1) or (stringMatch1 == true))
print "Missing or invalid vault_name." + "\n";
exit
end
validate1 = Chilkat::CkStringBuilder.new()
alphabet1 = Chilkat::CkStringBuilder.new()
success = validate1.Append(config.stringOf("vault_name"))
if (success != true)
print "Could not validate vault_name." + "\n";
exit
end
success = alphabet1.Append("abcdefghijklmnopqrstuvwxyz0123456789-")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate1.get_Length() < 3) or (validate1.get_Length() > 24))
print "Invalid vault_name length." + "\n";
exit
end
charIndex1 = 0
while (charIndex1 < validate1.get_Length())
if (alphabet1.Contains(validate1.getRange(charIndex1,1,false),true) != true)
print "Invalid character in vault_name." + "\n";
exit
end
charIndex1 = charIndex1 + 1
end
vaultName = Chilkat::CkStringBuilder.new()
vaultName.Append(config.stringOf("vault_name"))
letters = Chilkat::CkStringBuilder.new()
letters.Append("abcdefghijklmnopqrstuvwxyz")
if ((letters.Contains(vaultName.getRange(0,1,false),true) != true) or (vaultName.EndsWith("-",true) == true) or (vaultName.Contains("--",true) == true))
print "Invalid vault_name." + "\n";
exit
end
origin = Chilkat::CkStringBuilder.new()
success = origin.Append("https://")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = origin.Append(config.stringOf("vault_name"))
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = origin.Append(".vault.azure.net")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
stringCompare.SetString(config.stringOf("cert_name"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("cert_name") != 1) or (stringMatch2 == true))
print "Missing or invalid cert_name." + "\n";
exit
end
validate2 = Chilkat::CkStringBuilder.new()
alphabet2 = Chilkat::CkStringBuilder.new()
success = validate2.Append(config.stringOf("cert_name"))
if (success != true)
print "Could not validate cert_name." + "\n";
exit
end
success = alphabet2.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate2.get_Length() < 1) or (validate2.get_Length() > 127))
print "Invalid cert_name length." + "\n";
exit
end
charIndex2 = 0
while (charIndex2 < validate2.get_Length())
if (alphabet2.Contains(validate2.getRange(charIndex2,1,false),true) != true)
print "Invalid character in cert_name." + "\n";
exit
end
charIndex2 = charIndex2 + 1
end
stringCompare.SetString(config.stringOf("client_id"))
stringMatch3 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("client_id") != 1) or (stringMatch3 == true))
print "Missing or invalid client_id." + "\n";
exit
end
stringCompare.SetString(config.stringOf("client_secret"))
stringMatch4 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("client_secret") != 1) or (stringMatch4 == true))
print "Missing or invalid client_secret." + "\n";
exit
end
stringCompare.SetString(config.stringOf("tenant_id"))
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("tenant_id") != 1) or (stringMatch5 == true))
print "Missing or invalid tenant_id." + "\n";
exit
end
validate4 = Chilkat::CkStringBuilder.new()
alphabet4 = Chilkat::CkStringBuilder.new()
success = validate4.Append(config.stringOf("tenant_id"))
if (success != true)
print "Could not validate tenant GUID." + "\n";
exit
end
success = alphabet4.Append("0123456789abcdefABCDEF-")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate4.get_Length() < 36) or (validate4.get_Length() > 36))
print "Invalid tenant GUID length." + "\n";
exit
end
charIndex4 = 0
while (charIndex4 < validate4.get_Length())
if (alphabet4.Contains(validate4.getRange(charIndex4,1,false),true) != true)
print "Invalid character in tenant GUID." + "\n";
exit
end
charIndex4 = charIndex4 + 1
end
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(60)
http.put_VerboseLogging(false)
request = Chilkat::CkHttpRequest.new()
request.put_HttpVerb("GET")
response = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
readUrl = Chilkat::CkStringBuilder.new()
success = readUrl.Append(origin.getAsString())
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = readUrl.Append("/certificates/")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = readUrl.Append(config.stringOf("cert_name"))
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = readUrl.Append("?api-version=2026-04-01")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
cache = Chilkat::CkJsonObject.new()
cache.put_Strict(true)
expires = Chilkat::CkDateTime.new()
now = Chilkat::CkDateTime.new()
refresh = true
success = cache.LoadFile("qa_data/tokens/azureKeyVaultToken.json")
if (success == true)
stringCompare.SetString(cache.stringOf("tenant_id"))
stringMatch6 = stringCompare.ContentsEqual(config.stringOf("tenant_id"),true)
stringCompare.SetString(cache.stringOf("client_id"))
stringMatch7 = stringCompare.ContentsEqual(config.stringOf("client_id"),true)
stringCompare.SetString(cache.stringOf("resource"))
stringMatch8 = stringCompare.ContentsEqual("https://vault.azure.net",true)
if ((cache.JsonTypeOf("access_token") == 1) and (cache.JsonTypeOf("expires_at") == 1) and (stringMatch6 == true) and (stringMatch7 == true) and (stringMatch8 == true))
success = expires.SetFromTimestamp(cache.stringOf("expires_at"))
if (success == true)
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
stringCompare.SetString(cache.stringOf("access_token"))
stringMatch9 = stringCompare.ContentsEqual("",true)
if ((expires.DiffSeconds(now) > 60) and (stringMatch9 != true))
http.put_AuthToken(cache.stringOf("access_token"))
refresh = false
end
end
end
end
authHttp = Chilkat::CkHttp.new()
authHttp.put_RequireSslCertVerify(true)
authHttp.put_FollowRedirects(false)
authHttp.put_ConnectTimeout(20)
authHttp.put_ReadTimeout(60)
authRequest = Chilkat::CkHttpRequest.new()
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")
authResponse = Chilkat::CkHttpResponse.new()
authResult = Chilkat::CkJsonObject.new()
authResult.put_Strict(true)
authUrl = Chilkat::CkStringBuilder.new()
success = authUrl.Append("https://login.microsoftonline.com/")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = authUrl.Append(config.stringOf("tenant_id"))
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = authUrl.Append("/oauth2/v2.0/token")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
attempt = 0
delaySeconds = 1
retried401 = false
complete = false
jitter = Chilkat::CkPrng.new()
while ((attempt < 5) and (complete != true))
attempt = attempt + 1
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
if (refresh != true)
if (expires.DiffSeconds(now) <= 60)
refresh = true
end
end
if (refresh == true)
tokenExpires = Chilkat::CkDateTime.new()
success = tokenExpires.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
success = authHttp.HttpReq(authUrl.getAsString(),authRequest,authResponse)
if (success != true)
print "Token request failed." + "\n";
exit
end
if (authResponse.get_StatusCode() != 200)
print "Token request was rejected; no blind authentication retries." + "\n";
exit
end
success = authResult.Load(authResponse.bodyStr())
if (success != true)
print "Invalid token response." + "\n";
exit
end
stringCompare.SetString(authResult.stringOf("access_token"))
stringMatch10 = stringCompare.ContentsEqual("",true)
if ((authResult.JsonTypeOf("access_token") != 1) or (stringMatch10 == true))
print "Missing or invalid access_token." + "\n";
exit
end
stringCompare.SetString(authResult.stringOf("token_type"))
stringMatch11 = stringCompare.ContentsEqual("Bearer",true)
if (stringMatch11 != true)
print "Expected Bearer token." + "\n";
exit
end
if ((authResult.JsonTypeOf("expires_in") != 2))
print "Missing token lifetime." + "\n";
exit
end
validate9 = Chilkat::CkStringBuilder.new()
alphabet9 = Chilkat::CkStringBuilder.new()
success = validate9.Append(authResult.stringOf("expires_in"))
if (success != true)
print "Could not validate token lifetime." + "\n";
exit
end
success = alphabet9.Append("0123456789")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate9.get_Length() < 1) or (validate9.get_Length() > 8))
print "Invalid token lifetime length." + "\n";
exit
end
charIndex9 = 0
while (charIndex9 < validate9.get_Length())
if (alphabet9.Contains(validate9.getRange(charIndex9,1,false),true) != true)
print "Invalid character in token lifetime." + "\n";
exit
end
charIndex9 = charIndex9 + 1
end
tokenLifetime = authResult.IntOf("expires_in")
if ((tokenLifetime <= 60) or (tokenLifetime > 604800))
print "Unexpected token lifetime." + "\n";
exit
end
success = tokenExpires.AddSeconds(tokenLifetime)
if (success != true)
print "Could not calculate expiration." + "\n";
exit
end
tokenNow = Chilkat::CkDateTime.new()
success = tokenNow.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
if (tokenExpires.DiffSeconds(tokenNow) <= 60)
print "Token expired before it could be saved." + "\n";
exit
end
saved = Chilkat::CkJsonObject.new()
success = saved.UpdateString("access_token",authResult.stringOf("access_token"))
if (success != true)
print "Could not set access_token." + "\n";
exit
end
success = saved.UpdateString("expires_at",tokenExpires.getAsTimestamp(false))
if (success != true)
print "Could not set expires_at." + "\n";
exit
end
success = saved.UpdateString("tenant_id",config.stringOf("tenant_id"))
if (success != true)
print "Could not set tenant_id." + "\n";
exit
end
success = saved.UpdateString("client_id",config.stringOf("client_id"))
if (success != true)
print "Could not set client_id." + "\n";
exit
end
success = saved.UpdateString("resource","https://vault.azure.net")
if (success != true)
print "Could not set resource." + "\n";
exit
end
success = saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
if (success != true)
print "Could not save the private token file." + "\n";
exit
end
success = expires.SetFromTimestamp(saved.stringOf("expires_at"))
if (success != true)
print "Could not read cached expiry." + "\n";
exit
end
http.put_AuthToken(saved.stringOf("access_token"))
refresh = false
end
success = http.HttpReq(readUrl.getAsString(),request,response)
if (success != true)
print "Read transport failed; inspect diagnostics privately." + "\n";
exit
end
if (response.get_StatusCode() == 200)
success = result.Load(response.bodyStr())
if (success != true)
print "Invalid certificate response." + "\n";
exit
end
stringCompare.SetString(result.stringOf("id"))
stringMatch12 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("id") != 1) or (stringMatch12 == true))
print "Missing or invalid id." + "\n";
exit
end
stringCompare.SetString(result.stringOf("cer"))
stringMatch13 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("cer") != 1) or (stringMatch13 == true))
print "Missing or invalid cer." + "\n";
exit
end
complete = true
else
if ((response.get_StatusCode() == 401) and (retried401 != true))
refresh = true
retried401 = true
else
if ((response.get_StatusCode() != 429) and (response.get_StatusCode() != 500) and (response.get_StatusCode() != 502) and (response.get_StatusCode() != 503) and (response.get_StatusCode() != 504))
print "Non-retryable status or repeated 401." + "\n";
exit
end
if (attempt == 5)
print "Read retry limit reached." + "\n";
exit
end
waitSeconds = delaySeconds
retryAfter = response.getHeaderField("Retry-After")
stringCompare.SetString(retryAfter)
stringMatch14 = stringCompare.ContentsEqual("",true)
if (stringMatch14 != true)
retryText = Chilkat::CkStringBuilder.new()
retryText.Append(retryAfter)
numeric = true
digits = Chilkat::CkStringBuilder.new()
digits.Append("0123456789")
index = 0
while (index < retryText.get_Length())
if (digits.Contains(retryText.getRange(index,1,false),true) != true)
numeric = false
end
index = index + 1
end
if (numeric == true)
if (retryText.get_Length() > 8)
print "Retry-After exceeds this example budget; retry later." + "\n";
exit
end
waitSeconds = retryText.get_IntValue()
else
retryDate = Chilkat::CkDateTime.new()
success = retryDate.SetFromRfc822(retryAfter)
if (success != true)
print "Invalid Retry-After date." + "\n";
exit
end
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
waitSeconds = retryDate.DiffSeconds(now)
end
end
if (waitSeconds < 0)
waitSeconds = 0
end
if (waitSeconds > 30)
print "Retry-After exceeds this example budget; retry later without shortening it." + "\n";
exit
end
waitMs = waitSeconds * 1000 + jitter.RandomInt(0,250)
http.SleepMs(waitMs)
delaySeconds = delaySeconds * 2
end
end
end
if (complete != true)
print "Read did not complete within the attempt budget." + "\n";
exit
end
print "Example completed." + "\n";