Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

Azure Key Vault: Authenticate with a PS256 Certificate Assertion

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.

Register the public certificate as an application credential, then provide client_id, tenant_id and client_pfx_password. The authentication certificate is separate from certificates stored in the vault. Signs a short-lived PS256 JWT with x5t#S256, exact tenant token-endpoint audience, issuer/subject client ID and a random jti. Requires synchronized time. The secret-free exchange still requires protecting the local private key and returned token. Does not print the assertion.

Microsoft reference

Chilkat B4X Downloads

B4X
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

If config.JsonTypeOf("client_pfx_password") <> 1 Then
    Log("Missing client_pfx_password string.")
    Return
End If

Dim clientCert As ChilkatCert
clientCert.Initialize("clientCert")
success = clientCert.LoadPfxFile("qa_data/azure/client-auth.pfx", config.StringOf("client_pfx_password"))
If success <> True Then
    Log("Could not load client authentication PFX.")
    Return
End If

If clientCert.IsRsa <> True Then
    Log("PS256 client assertion requires RSA.")
    Return
End If

Dim signingKey As ChilkatPrivateKey
signingKey.Initialize("signingKey")
success = clientCert.GetPrivateKey(signingKey)
If success <> True Then
    Log("Client certificate needs a private key.")
    Return
End If

Dim certificateDer As ChilkatBinData
certificateDer.Initialize
success = certificateDer.AppendEncoded(clientCert.GetEncoded, "base64")
If success <> True Then
    Log("Could not encode client certificate.")
    Return
End If

Dim thumbprint As String = certificateDer.GetHash("sha256", "base64url")
If certificateDer.LastMethodSuccess <> True Then
    Log("Could not hash certificate.")
    Return
End If

Dim header As ChilkatJsonObject
header.Initialize
Dim claims As ChilkatJsonObject
claims.Initialize
Dim jwt As ChilkatJwt
jwt.Initialize
Dim random As ChilkatPrng
random.Initialize
Dim jwtId As String = random.GenRandom(32, "hex")
If random.LastMethodSuccess <> True Then
    Log("Could not generate assertion ID.")
    Return
End If

success = header.UpdateString("alg", "PS256")
If success <> True Then
    Log("Could not set alg.")
    Return
End If

success = header.UpdateString("typ", "JWT")
If success <> True Then
    Log("Could not set typ.")
    Return
End If

success = header.UpdateString("x5t#S256", thumbprint)
If success <> True Then
    Log("Could not set x5t#S256.")
    Return
End If

success = claims.UpdateString("iss", config.StringOf("client_id"))
If success <> True Then
    Log("Could not set iss.")
    Return
End If

success = claims.UpdateString("sub", config.StringOf("client_id"))
If success <> True Then
    Log("Could not set sub.")
    Return
End If

success = claims.UpdateString("aud", tokenUrl.GetAsString)
If success <> True Then
    Log("Could not set aud.")
    Return
End If

success = claims.UpdateString("jti", jwtId)
If success <> True Then
    Log("Could not set jti.")
    Return
End If

success = claims.UpdateInt("nbf", jwt.GenNumericDate(-30))
If success <> True Then
    Log("Could not set assertion start.")
    Return
End If

success = claims.UpdateInt("iat", jwt.GenNumericDate(0))
If success <> True Then
    Log("Could not set assertion issue time.")
    Return
End If

success = claims.UpdateInt("exp", jwt.GenNumericDate(300))
If success <> True Then
    Log("Could not set assertion expiration.")
    Return
End If

Dim assertion As String = jwt.CreateJwtPk(header.Emit, claims.Emit, signingKey)
If jwt.LastMethodSuccess <> True Then
    Log("Could not sign the client assertion.")
    Return
End If

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 validate7 As ChilkatStringBuilder
validate7.Initialize
Dim alphabet7 As ChilkatStringBuilder
alphabet7.Initialize
success = validate7.Append(result.StringOf("expires_in"))
If success <> True Then
    Log("Could not validate token lifetime.")
    Return
End If

success = alphabet7.Append("0123456789")
If success <> True Then
    Log("Could not initialize validation.")
    Return
End If

If (validate7.Length < 1) Or (validate7.Length > 8) Then
    Log("Invalid token lifetime length.")
    Return
End If

Dim charIndex7 As Int = 0
Do While (charIndex7 < validate7.Length)
    If alphabet7.Contains(validate7.GetRange(charIndex7, 1, False), True) <> True Then
        Log("Invalid character in token lifetime.")
        Return
    End If

    charIndex7 = charIndex7 + 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.")