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