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 VBScript Downloads
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)
success = 0
set stringCompare = CreateObject("Chilkat.StringBuilder")
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' Keep this configuration private, outside public web content and source control.
set config = CreateObject("Chilkat.JsonObject")
config.Strict = 1
success = config.LoadFile("qa_data/azure/keyvault.json")
If (success <> 1) Then
outFile.WriteLine("Could not load private Key Vault configuration.")
WScript.Quit
End If
success = stringCompare.SetString(config.StringOf("vault_name"))
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((config.JsonTypeOf("vault_name") <> 1) Or (stringMatch1 = 1)) Then
outFile.WriteLine("Missing or invalid vault_name.")
WScript.Quit
End If
set validate1 = CreateObject("Chilkat.StringBuilder")
set alphabet1 = CreateObject("Chilkat.StringBuilder")
success = validate1.Append(config.StringOf("vault_name"))
If (success <> 1) Then
outFile.WriteLine("Could not validate vault_name.")
WScript.Quit
End If
success = alphabet1.Append("abcdefghijklmnopqrstuvwxyz0123456789-")
If (success <> 1) Then
outFile.WriteLine("Could not initialize validation.")
WScript.Quit
End If
If ((validate1.Length < 3) Or (validate1.Length > 24)) Then
outFile.WriteLine("Invalid vault_name length.")
WScript.Quit
End If
charIndex1 = 0
Do While (charIndex1 < validate1.Length)
If (alphabet1.Contains(validate1.GetRange(charIndex1,1,0),1) <> 1) Then
outFile.WriteLine("Invalid character in vault_name.")
WScript.Quit
End If
charIndex1 = charIndex1 + 1
Loop
set vaultName = CreateObject("Chilkat.StringBuilder")
success = vaultName.Append(config.StringOf("vault_name"))
set letters = CreateObject("Chilkat.StringBuilder")
success = letters.Append("abcdefghijklmnopqrstuvwxyz")
If ((letters.Contains(vaultName.GetRange(0,1,0),1) <> 1) Or (vaultName.EndsWith("-",1) = 1) Or (vaultName.Contains("--",1) = 1)) Then
outFile.WriteLine("Invalid vault_name.")
WScript.Quit
End If
set origin = CreateObject("Chilkat.StringBuilder")
success = origin.Append("https://")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = origin.Append(config.StringOf("vault_name"))
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = origin.Append(".vault.azure.net")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = stringCompare.SetString(config.StringOf("cert_name"))
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((config.JsonTypeOf("cert_name") <> 1) Or (stringMatch2 = 1)) Then
outFile.WriteLine("Missing or invalid cert_name.")
WScript.Quit
End If
set validate2 = CreateObject("Chilkat.StringBuilder")
set alphabet2 = CreateObject("Chilkat.StringBuilder")
success = validate2.Append(config.StringOf("cert_name"))
If (success <> 1) Then
outFile.WriteLine("Could not validate cert_name.")
WScript.Quit
End If
success = alphabet2.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
If (success <> 1) Then
outFile.WriteLine("Could not initialize validation.")
WScript.Quit
End If
If ((validate2.Length < 1) Or (validate2.Length > 127)) Then
outFile.WriteLine("Invalid cert_name length.")
WScript.Quit
End If
charIndex2 = 0
Do While (charIndex2 < validate2.Length)
If (alphabet2.Contains(validate2.GetRange(charIndex2,1,0),1) <> 1) Then
outFile.WriteLine("Invalid character in cert_name.")
WScript.Quit
End If
charIndex2 = charIndex2 + 1
Loop
success = stringCompare.SetString(config.StringOf("client_id"))
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((config.JsonTypeOf("client_id") <> 1) Or (stringMatch3 = 1)) Then
outFile.WriteLine("Missing or invalid client_id.")
WScript.Quit
End If
success = stringCompare.SetString(config.StringOf("client_secret"))
stringMatch4 = stringCompare.ContentsEqual("",1)
If ((config.JsonTypeOf("client_secret") <> 1) Or (stringMatch4 = 1)) Then
outFile.WriteLine("Missing or invalid client_secret.")
WScript.Quit
End If
success = stringCompare.SetString(config.StringOf("tenant_id"))
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((config.JsonTypeOf("tenant_id") <> 1) Or (stringMatch5 = 1)) Then
outFile.WriteLine("Missing or invalid tenant_id.")
WScript.Quit
End If
set validate4 = CreateObject("Chilkat.StringBuilder")
set alphabet4 = CreateObject("Chilkat.StringBuilder")
success = validate4.Append(config.StringOf("tenant_id"))
If (success <> 1) Then
outFile.WriteLine("Could not validate tenant GUID.")
WScript.Quit
End If
success = alphabet4.Append("0123456789abcdefABCDEF-")
If (success <> 1) Then
outFile.WriteLine("Could not initialize validation.")
WScript.Quit
End If
If ((validate4.Length < 36) Or (validate4.Length > 36)) Then
outFile.WriteLine("Invalid tenant GUID length.")
WScript.Quit
End If
charIndex4 = 0
Do While (charIndex4 < validate4.Length)
If (alphabet4.Contains(validate4.GetRange(charIndex4,1,0),1) <> 1) Then
outFile.WriteLine("Invalid character in tenant GUID.")
WScript.Quit
End If
charIndex4 = charIndex4 + 1
Loop
set http = CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 20
http.ReadTimeout = 60
http.VerboseLogging = 0
set request = CreateObject("Chilkat.HttpRequest")
request.HttpVerb = "GET"
set response = CreateObject("Chilkat.HttpResponse")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1
set readUrl = CreateObject("Chilkat.StringBuilder")
success = readUrl.Append(origin.GetAsString())
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = readUrl.Append("/certificates/")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = readUrl.Append(config.StringOf("cert_name"))
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = readUrl.Append("?api-version=2026-04-01")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
set cache = CreateObject("Chilkat.JsonObject")
cache.Strict = 1
set expires = CreateObject("Chilkat.CkDateTime")
set now = CreateObject("Chilkat.CkDateTime")
refresh = 1
success = cache.LoadFile("qa_data/tokens/azureKeyVaultToken.json")
If (success = 1) Then
success = stringCompare.SetString(cache.StringOf("tenant_id"))
stringMatch6 = stringCompare.ContentsEqual(config.StringOf("tenant_id"),1)
success = stringCompare.SetString(cache.StringOf("client_id"))
stringMatch7 = stringCompare.ContentsEqual(config.StringOf("client_id"),1)
success = stringCompare.SetString(cache.StringOf("resource"))
stringMatch8 = stringCompare.ContentsEqual("https://vault.azure.net",1)
If ((cache.JsonTypeOf("access_token") = 1) And (cache.JsonTypeOf("expires_at") = 1) And (stringMatch6 = 1) And (stringMatch7 = 1) And (stringMatch8 = 1)) Then
success = expires.SetFromTimestamp(cache.StringOf("expires_at"))
If (success = 1) Then
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read time.")
WScript.Quit
End If
success = stringCompare.SetString(cache.StringOf("access_token"))
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((expires.DiffSeconds(now) > 60) And (stringMatch9 <> 1)) Then
http.AuthToken = cache.StringOf("access_token")
refresh = 0
End If
End If
End If
End If
set authHttp = CreateObject("Chilkat.Http")
authHttp.RequireSslCertVerify = 1
authHttp.FollowRedirects = 0
authHttp.ConnectTimeout = 20
authHttp.ReadTimeout = 60
set authRequest = CreateObject("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"
set authResponse = CreateObject("Chilkat.HttpResponse")
set authResult = CreateObject("Chilkat.JsonObject")
authResult.Strict = 1
set authUrl = CreateObject("Chilkat.StringBuilder")
success = authUrl.Append("https://login.microsoftonline.com/")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = authUrl.Append(config.StringOf("tenant_id"))
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
success = authUrl.Append("/oauth2/v2.0/token")
If (success <> 1) Then
outFile.WriteLine("Could not construct URL or identifier.")
WScript.Quit
End If
attempt = 0
delaySeconds = 1
retried401 = 0
complete = 0
set jitter = CreateObject("Chilkat.Prng")
Do While ((attempt < 5) And (complete <> 1))
attempt = attempt + 1
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read time.")
WScript.Quit
End If
If (refresh <> 1) Then
If (expires.DiffSeconds(now) <= 60) Then
refresh = 1
End If
End If
If (refresh = 1) Then
set tokenExpires = CreateObject("Chilkat.CkDateTime")
success = tokenExpires.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read time.")
WScript.Quit
End If
success = authHttp.HttpReq(authUrl.GetAsString(),authRequest,authResponse)
If (success <> 1) Then
outFile.WriteLine("Token request failed.")
WScript.Quit
End If
If (authResponse.StatusCode <> 200) Then
outFile.WriteLine("Token request was rejected; no blind authentication retries.")
WScript.Quit
End If
success = authResult.Load(authResponse.BodyStr)
If (success <> 1) Then
outFile.WriteLine("Invalid token response.")
WScript.Quit
End If
success = stringCompare.SetString(authResult.StringOf("access_token"))
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((authResult.JsonTypeOf("access_token") <> 1) Or (stringMatch10 = 1)) Then
outFile.WriteLine("Missing or invalid access_token.")
WScript.Quit
End If
success = stringCompare.SetString(authResult.StringOf("token_type"))
stringMatch11 = stringCompare.ContentsEqual("Bearer",1)
If (stringMatch11 <> 1) Then
outFile.WriteLine("Expected Bearer token.")
WScript.Quit
End If
If ((authResult.JsonTypeOf("expires_in") <> 2)) Then
outFile.WriteLine("Missing token lifetime.")
WScript.Quit
End If
set validate9 = CreateObject("Chilkat.StringBuilder")
set alphabet9 = CreateObject("Chilkat.StringBuilder")
success = validate9.Append(authResult.StringOf("expires_in"))
If (success <> 1) Then
outFile.WriteLine("Could not validate token lifetime.")
WScript.Quit
End If
success = alphabet9.Append("0123456789")
If (success <> 1) Then
outFile.WriteLine("Could not initialize validation.")
WScript.Quit
End If
If ((validate9.Length < 1) Or (validate9.Length > 8)) Then
outFile.WriteLine("Invalid token lifetime length.")
WScript.Quit
End If
charIndex9 = 0
Do While (charIndex9 < validate9.Length)
If (alphabet9.Contains(validate9.GetRange(charIndex9,1,0),1) <> 1) Then
outFile.WriteLine("Invalid character in token lifetime.")
WScript.Quit
End If
charIndex9 = charIndex9 + 1
Loop
tokenLifetime = authResult.IntOf("expires_in")
If ((tokenLifetime <= 60) Or (tokenLifetime > 604800)) Then
outFile.WriteLine("Unexpected token lifetime.")
WScript.Quit
End If
success = tokenExpires.AddSeconds(tokenLifetime)
If (success <> 1) Then
outFile.WriteLine("Could not calculate expiration.")
WScript.Quit
End If
set tokenNow = CreateObject("Chilkat.CkDateTime")
success = tokenNow.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read time.")
WScript.Quit
End If
If (tokenExpires.DiffSeconds(tokenNow) <= 60) Then
outFile.WriteLine("Token expired before it could be saved.")
WScript.Quit
End If
set saved = CreateObject("Chilkat.JsonObject")
success = saved.UpdateString("access_token",authResult.StringOf("access_token"))
If (success <> 1) Then
outFile.WriteLine("Could not set access_token.")
WScript.Quit
End If
success = saved.UpdateString("expires_at",tokenExpires.GetAsTimestamp(0))
If (success <> 1) Then
outFile.WriteLine("Could not set expires_at.")
WScript.Quit
End If
success = saved.UpdateString("tenant_id",config.StringOf("tenant_id"))
If (success <> 1) Then
outFile.WriteLine("Could not set tenant_id.")
WScript.Quit
End If
success = saved.UpdateString("client_id",config.StringOf("client_id"))
If (success <> 1) Then
outFile.WriteLine("Could not set client_id.")
WScript.Quit
End If
success = saved.UpdateString("resource","https://vault.azure.net")
If (success <> 1) Then
outFile.WriteLine("Could not set resource.")
WScript.Quit
End If
success = saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
If (success <> 1) Then
outFile.WriteLine("Could not save the private token file.")
WScript.Quit
End If
success = expires.SetFromTimestamp(saved.StringOf("expires_at"))
If (success <> 1) Then
outFile.WriteLine("Could not read cached expiry.")
WScript.Quit
End If
http.AuthToken = saved.StringOf("access_token")
refresh = 0
End If
success = http.HttpReq(readUrl.GetAsString(),request,response)
If (success <> 1) Then
outFile.WriteLine("Read transport failed; inspect diagnostics privately.")
WScript.Quit
End If
If (response.StatusCode = 200) Then
success = result.Load(response.BodyStr)
If (success <> 1) Then
outFile.WriteLine("Invalid certificate response.")
WScript.Quit
End If
success = stringCompare.SetString(result.StringOf("id"))
stringMatch12 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("id") <> 1) Or (stringMatch12 = 1)) Then
outFile.WriteLine("Missing or invalid id.")
WScript.Quit
End If
success = stringCompare.SetString(result.StringOf("cer"))
stringMatch13 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("cer") <> 1) Or (stringMatch13 = 1)) Then
outFile.WriteLine("Missing or invalid cer.")
WScript.Quit
End If
complete = 1
Else
If ((response.StatusCode = 401) And (retried401 <> 1)) Then
refresh = 1
retried401 = 1
Else
If ((response.StatusCode <> 429) And (response.StatusCode <> 500) And (response.StatusCode <> 502) And (response.StatusCode <> 503) And (response.StatusCode <> 504)) Then
outFile.WriteLine("Non-retryable status or repeated 401.")
WScript.Quit
End If
If (attempt = 5) Then
outFile.WriteLine("Read retry limit reached.")
WScript.Quit
End If
waitSeconds = delaySeconds
retryAfter = response.GetHeaderField("Retry-After")
success = stringCompare.SetString(retryAfter)
stringMatch14 = stringCompare.ContentsEqual("",1)
If (stringMatch14 <> 1) Then
set retryText = CreateObject("Chilkat.StringBuilder")
success = retryText.Append(retryAfter)
numeric = 1
set digits = CreateObject("Chilkat.StringBuilder")
success = digits.Append("0123456789")
index = 0
Do While (index < retryText.Length)
If (digits.Contains(retryText.GetRange(index,1,0),1) <> 1) Then
numeric = 0
End If
index = index + 1
Loop
If (numeric = 1) Then
If (retryText.Length > 8) Then
outFile.WriteLine("Retry-After exceeds this example budget; retry later.")
WScript.Quit
End If
waitSeconds = retryText.IntValue
Else
set retryDate = CreateObject("Chilkat.CkDateTime")
success = retryDate.SetFromRfc822(retryAfter)
If (success <> 1) Then
outFile.WriteLine("Invalid Retry-After date.")
WScript.Quit
End If
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read time.")
WScript.Quit
End If
waitSeconds = retryDate.DiffSeconds(now)
End If
End If
If (waitSeconds < 0) Then
waitSeconds = 0
End If
If (waitSeconds > 30) Then
outFile.WriteLine("Retry-After exceeds this example budget; retry later without shortening it.")
WScript.Quit
End If
waitMs = waitSeconds * 1000 + jitter.RandomInt(0,250)
http.SleepMs waitMs
delaySeconds = delaySeconds * 2
End If
End If
Loop
If (complete <> 1) Then
outFile.WriteLine("Read did not complete within the attempt budget.")
WScript.Quit
End If
outFile.WriteLine("Example completed.")
outFile.Close