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 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("client_id"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (config.JsonTypeOf("client_id") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid client_id.")
Return
End If
stringCompare.SetString(config.StringOf("tenant_id"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (config.JsonTypeOf("tenant_id") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid tenant_id.")
Return
End If
Dim validate5 As ChilkatStringBuilder
validate5.Initialize
Dim alphabet5 As ChilkatStringBuilder
alphabet5.Initialize
success = validate5.Append(config.StringOf("tenant_id"))
If success <> True Then
Log("Could not validate tenant GUID.")
Return
End If
success = alphabet5.Append("0123456789abcdefABCDEF-")
If success <> True Then
Log("Could not initialize validation.")
Return
End If
If (validate5.Length < 36) Or (validate5.Length > 36) Then
Log("Invalid tenant GUID length.")
Return
End If
Dim charIndex5 As Int = 0
Do While (charIndex5 < validate5.Length)
If alphabet5.Contains(validate5.GetRange(charIndex5, 1, False), True) <> True Then
Log("Invalid character in tenant GUID.")
Return
End If
charIndex5 = charIndex5 + 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 tokenUrl As ChilkatStringBuilder
tokenUrl.Initialize
success = tokenUrl.Append("https://login.microsoftonline.com/")
If success <> True Then
Log("Could not construct URL or identifier.")
Return
End If
success = tokenUrl.Append(config.StringOf("tenant_id"))
If success <> True Then
Log("Could not construct URL or identifier.")
Return
End If
success = tokenUrl.Append("/oauth2/v2.0/token")
If success <> True Then
Log("Could not construct URL or identifier.")
Return
End If
' Your trusted workload runtime must refresh this projected token file.
Dim projected As ChilkatStringBuilder
projected.Initialize
success = projected.LoadFile("qa_data/azure/federated-token.jwt", "utf-8")
If success <> True Then
Log("Could not read projected workload token.")
Return
End If
success = projected.Trim
If success <> True Then
Log("Could not trim token.")
Return
End If
If projected.Length = 0 Then
Log("Projected token is empty.")
Return
End If
Dim assertion As String = projected.GetAsString
request.HttpVerb = "POST"
request.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)
Dim tokenExpires As ChilkatDateTime
tokenExpires.Initialize
success = tokenExpires.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read time.")
Return
End If
success = http.HttpReq(tokenUrl.GetAsString, request, response)
If success <> True Then
Log("Token exchange failed; inspect diagnostics privately.")
Return
End If
If response.StatusCode <> 200 Then
Log("Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.")
Return
End If
success = result.Load(response.BodyStr)
If success <> True Then
Log("Invalid JSON response.")
Return
End If
stringCompare.SetString(result.StringOf("access_token"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("access_token") <> 1) Or (stringMatch3 = True) Then
Log("Missing or invalid access_token.")
Return
End If
stringCompare.SetString(result.StringOf("token_type"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("Bearer", True)
If stringMatch4 <> True Then
Log("Expected Bearer token.")
Return
End If
If (result.JsonTypeOf("expires_in") <> 2) Then
Log("Missing token lifetime.")
Return
End If
Dim validate8 As ChilkatStringBuilder
validate8.Initialize
Dim alphabet8 As ChilkatStringBuilder
alphabet8.Initialize
success = validate8.Append(result.StringOf("expires_in"))
If success <> True Then
Log("Could not validate token lifetime.")
Return
End If
success = alphabet8.Append("0123456789")
If success <> True Then
Log("Could not initialize validation.")
Return
End If
If (validate8.Length < 1) Or (validate8.Length > 8) Then
Log("Invalid token lifetime length.")
Return
End If
Dim charIndex8 As Int = 0
Do While (charIndex8 < validate8.Length)
If alphabet8.Contains(validate8.GetRange(charIndex8, 1, False), True) <> True Then
Log("Invalid character in token lifetime.")
Return
End If
charIndex8 = charIndex8 + 1
Loop
Dim tokenLifetime As Int = result.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", result.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.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
If success <> True Then
Log("Could not save the private token file.")
Return
End If
Log("Example completed.")