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