Azure Key Vault: Get a Token with Azure VM Managed Identity
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.
Run on an Azure VM with an enabled system-assigned identity, or set managed_identity_client_id for an attached user-assigned identity. The fixed link-local endpoint and Metadata header are specific to VM IMDS, not App Service. Proxying and redirects are disabled. Grant the identity appropriate vault data-plane permissions. Saves the same private token format as the other examples; does not print tokens. The example stops on IMDS errors; production IMDS retries must follow its service-specific guidance.
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
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
' Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
http.UseIEProxy = False
http.ProxyDomain = ""
http.ConnectTimeout = 5
request.HttpVerb = "GET"
request.AddHeader("Metadata", "true")
request.AddParam("api-version", "2018-02-01")
request.AddParam("resource", "https://vault.azure.net")
If config.HasMember("managed_identity_client_id") = True Then
stringCompare.SetString(config.StringOf("managed_identity_client_id"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (config.JsonTypeOf("managed_identity_client_id") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid managed_identity_client_id.")
Return
End If
request.AddParam("client_id", config.StringOf("managed_identity_client_id"))
End If
Dim tokenExpires As ChilkatDateTime
tokenExpires.Initialize
success = tokenExpires.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read time.")
Return
End If
success = http.HttpReq("http://169.254.169.254/metadata/identity/oauth2/token", request, response)
If success <> True Then
Log("IMDS request failed; run on an Azure VM with managed identity enabled.")
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 stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("access_token") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid access_token.")
Return
End If
stringCompare.SetString(result.StringOf("token_type"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("Bearer", True)
If stringMatch3 <> True Then
Log("Expected Bearer token.")
Return
End If
If (result.JsonTypeOf("expires_in") <> 2) And (result.JsonTypeOf("expires_in") <> 1) Then
Log("Missing token lifetime.")
Return
End If
Dim validate6 As ChilkatStringBuilder
validate6.Initialize
Dim alphabet6 As ChilkatStringBuilder
alphabet6.Initialize
success = validate6.Append(result.StringOf("expires_in"))
If success <> True Then
Log("Could not validate token lifetime.")
Return
End If
success = alphabet6.Append("0123456789")
If success <> True Then
Log("Could not initialize validation.")
Return
End If
If (validate6.Length < 1) Or (validate6.Length > 8) Then
Log("Invalid token lifetime length.")
Return
End If
Dim charIndex6 As Int = 0
Do While (charIndex6 < validate6.Length)
If alphabet6.Contains(validate6.GetRange(charIndex6, 1, False), True) <> True Then
Log("Invalid character in token lifetime.")
Return
End If
charIndex6 = charIndex6 + 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.")