Azure Key Vault: Exchange a Workload Identity Token
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.
Configure an Entra federated identity credential with the exact external issuer, subject, and audience (commonly api://AzureADTokenExchange). Provide client_id and tenant_id. Have the trusted workload runtime supply a fresh projected JWT at qa_data/azure/federated-token.jwt before each exchange; adapt this path to your runtime-provided token path. The application forwards this assertion to the fixed tenant endpoint; Entra validates the federation trust. This does not mint or locally trust an arbitrary external token.
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("client_id"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("client_id") != 1) or (stringMatch1 == true))
print "Missing or invalid client_id." + "\n";
exit
end
stringCompare.SetString(config.stringOf("tenant_id"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((config.JsonTypeOf("tenant_id") != 1) or (stringMatch2 == true))
print "Missing or invalid tenant_id." + "\n";
exit
end
validate5 = Chilkat::CkStringBuilder.new()
alphabet5 = Chilkat::CkStringBuilder.new()
success = validate5.Append(config.stringOf("tenant_id"))
if (success != true)
print "Could not validate tenant GUID." + "\n";
exit
end
success = alphabet5.Append("0123456789abcdefABCDEF-")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate5.get_Length() < 36) or (validate5.get_Length() > 36))
print "Invalid tenant GUID length." + "\n";
exit
end
charIndex5 = 0
while (charIndex5 < validate5.get_Length())
if (alphabet5.Contains(validate5.getRange(charIndex5,1,false),true) != true)
print "Invalid character in tenant GUID." + "\n";
exit
end
charIndex5 = charIndex5 + 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)
tokenUrl = Chilkat::CkStringBuilder.new()
success = tokenUrl.Append("https://login.microsoftonline.com/")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = tokenUrl.Append(config.stringOf("tenant_id"))
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
success = tokenUrl.Append("/oauth2/v2.0/token")
if (success != true)
print "Could not construct URL or identifier." + "\n";
exit
end
# Your trusted workload runtime must refresh this projected token file.
projected = Chilkat::CkStringBuilder.new()
success = projected.LoadFile("qa_data/azure/federated-token.jwt","utf-8")
if (success != true)
print "Could not read projected workload token." + "\n";
exit
end
success = projected.Trim()
if (success != true)
print "Could not trim token." + "\n";
exit
end
if (projected.get_Length() == 0)
print "Projected token is empty." + "\n";
exit
end
assertion = projected.getAsString()
request.put_HttpVerb("POST")
request.put_ContentType("application/x-www-form-urlencoded")
request.AddParam("client_id",config.stringOf("client_id"))
request.AddParam("scope","https://vault.azure.net/.default")
request.AddParam("grant_type","client_credentials")
request.AddParam("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
request.AddParam("client_assertion",assertion)
tokenExpires = Chilkat::CkDateTime.new()
success = tokenExpires.SetFromCurrentSystemTime()
if (success != true)
print "Could not read time." + "\n";
exit
end
success = http.HttpReq(tokenUrl.getAsString(),request,response)
if (success != true)
print "Token exchange failed; inspect diagnostics privately." + "\n";
exit
end
if (response.get_StatusCode() != 200)
print "Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying." + "\n";
exit
end
success = result.Load(response.bodyStr())
if (success != true)
print "Invalid JSON response." + "\n";
exit
end
stringCompare.SetString(result.stringOf("access_token"))
stringMatch3 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("access_token") != 1) or (stringMatch3 == true))
print "Missing or invalid access_token." + "\n";
exit
end
stringCompare.SetString(result.stringOf("token_type"))
stringMatch4 = stringCompare.ContentsEqual("Bearer",true)
if (stringMatch4 != true)
print "Expected Bearer token." + "\n";
exit
end
if ((result.JsonTypeOf("expires_in") != 2))
print "Missing token lifetime." + "\n";
exit
end
validate8 = Chilkat::CkStringBuilder.new()
alphabet8 = Chilkat::CkStringBuilder.new()
success = validate8.Append(result.stringOf("expires_in"))
if (success != true)
print "Could not validate token lifetime." + "\n";
exit
end
success = alphabet8.Append("0123456789")
if (success != true)
print "Could not initialize validation." + "\n";
exit
end
if ((validate8.get_Length() < 1) or (validate8.get_Length() > 8))
print "Invalid token lifetime length." + "\n";
exit
end
charIndex8 = 0
while (charIndex8 < validate8.get_Length())
if (alphabet8.Contains(validate8.getRange(charIndex8,1,false),true) != true)
print "Invalid character in token lifetime." + "\n";
exit
end
charIndex8 = charIndex8 + 1
end
tokenLifetime = result.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",result.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.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
if (success != true)
print "Could not save the private token file." + "\n";
exit
end
print "Example completed." + "\n";