Sample code for 30+ languages & platforms
PowerShell 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 PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

$stringCompare = New-Object Chilkat.StringBuilder
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this configuration private, outside public web content and source control.
$config = New-Object Chilkat.JsonObject
$config.Strict = $true
$success = $config.LoadFile("qa_data/azure/keyvault.json")
if ($success -ne $true) {
    $("Could not load private Key Vault configuration.")
    exit
}

$stringCompare.SetString($config.StringOf("client_id"))
$stringMatch1 = $stringCompare.ContentsEqual("",$true)
if (($config.JsonTypeOf("client_id") -ne 1) -or ($stringMatch1 -eq $true)) {
    $("Missing or invalid client_id.")
    exit
}

$stringCompare.SetString($config.StringOf("tenant_id"))
$stringMatch2 = $stringCompare.ContentsEqual("",$true)
if (($config.JsonTypeOf("tenant_id") -ne 1) -or ($stringMatch2 -eq $true)) {
    $("Missing or invalid tenant_id.")
    exit
}

$validate5 = New-Object Chilkat.StringBuilder
$alphabet5 = New-Object Chilkat.StringBuilder
$success = $validate5.Append($config.StringOf("tenant_id"))
if ($success -ne $true) {
    $("Could not validate tenant GUID.")
    exit
}

$success = $alphabet5.Append("0123456789abcdefABCDEF-")
if ($success -ne $true) {
    $("Could not initialize validation.")
    exit
}

if (($validate5.Length -lt 36) -or ($validate5.Length -gt 36)) {
    $("Invalid tenant GUID length.")
    exit
}

$charIndex5 = 0
while (($charIndex5 -lt $validate5.Length)) {
    if ($alphabet5.Contains($validate5.GetRange($charIndex5,1,$false),$true) -ne $true) {
        $("Invalid character in tenant GUID.")
        exit
    }

    $charIndex5 = $charIndex5 + 1
}

$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
$http.FollowRedirects = $false
$http.ConnectTimeout = 20
$http.ReadTimeout = 60
$http.VerboseLogging = $false
$request = New-Object Chilkat.HttpRequest
$request.HttpVerb = "GET"
$response = New-Object Chilkat.HttpResponse
$result = New-Object Chilkat.JsonObject
$result.Strict = $true
$tokenUrl = New-Object Chilkat.StringBuilder
$success = $tokenUrl.Append("https://login.microsoftonline.com/")
if ($success -ne $true) {
    $("Could not construct URL or identifier.")
    exit
}

$success = $tokenUrl.Append($config.StringOf("tenant_id"))
if ($success -ne $true) {
    $("Could not construct URL or identifier.")
    exit
}

$success = $tokenUrl.Append("/oauth2/v2.0/token")
if ($success -ne $true) {
    $("Could not construct URL or identifier.")
    exit
}

if ($config.JsonTypeOf("client_pfx_password") -ne 1) {
    $("Missing client_pfx_password string.")
    exit
}

$clientCert = New-Object Chilkat.Cert
$success = $clientCert.LoadPfxFile("qa_data/azure/client-auth.pfx",$config.StringOf("client_pfx_password"))
if ($success -ne $true) {
    $("Could not load client authentication PFX.")
    exit
}

if ($clientCert.IsRsa() -ne $true) {
    $("PS256 client assertion requires RSA.")
    exit
}

$signingKey = New-Object Chilkat.PrivateKey
$success = $clientCert.GetPrivateKey($signingKey)
if ($success -ne $true) {
    $("Client certificate needs a private key.")
    exit
}

$certificateDer = New-Object Chilkat.BinData
$success = $certificateDer.AppendEncoded($clientCert.GetEncoded(),"base64")
if ($success -ne $true) {
    $("Could not encode client certificate.")
    exit
}

$thumbprint = $certificateDer.GetHash("sha256","base64url")
if ($certificateDer.LastMethodSuccess -ne $true) {
    $("Could not hash certificate.")
    exit
}

$header = New-Object Chilkat.JsonObject
$claims = New-Object Chilkat.JsonObject
$jwt = New-Object Chilkat.Jwt
$random = New-Object Chilkat.Prng
$jwtId = $random.GenRandom(32,"hex")
if ($random.LastMethodSuccess -ne $true) {
    $("Could not generate assertion ID.")
    exit
}

$success = $header.UpdateString("alg","PS256")
if ($success -ne $true) {
    $("Could not set alg.")
    exit
}

$success = $header.UpdateString("typ","JWT")
if ($success -ne $true) {
    $("Could not set typ.")
    exit
}

$success = $header.UpdateString("x5t#S256",$thumbprint)
if ($success -ne $true) {
    $("Could not set x5t#S256.")
    exit
}

$success = $claims.UpdateString("iss",$config.StringOf("client_id"))
if ($success -ne $true) {
    $("Could not set iss.")
    exit
}

$success = $claims.UpdateString("sub",$config.StringOf("client_id"))
if ($success -ne $true) {
    $("Could not set sub.")
    exit
}

$success = $claims.UpdateString("aud",$tokenUrl.GetAsString())
if ($success -ne $true) {
    $("Could not set aud.")
    exit
}

$success = $claims.UpdateString("jti",$jwtId)
if ($success -ne $true) {
    $("Could not set jti.")
    exit
}

$success = $claims.UpdateInt("nbf",$jwt.GenNumericDate(-30))
if ($success -ne $true) {
    $("Could not set assertion start.")
    exit
}

$success = $claims.UpdateInt("iat",$jwt.GenNumericDate(0))
if ($success -ne $true) {
    $("Could not set assertion issue time.")
    exit
}

$success = $claims.UpdateInt("exp",$jwt.GenNumericDate(300))
if ($success -ne $true) {
    $("Could not set assertion expiration.")
    exit
}

$assertion = $jwt.CreateJwtPk($header.Emit(),$claims.Emit(),$signingKey)
if ($jwt.LastMethodSuccess -ne $true) {
    $("Could not sign the client assertion.")
    exit
}

$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)
$tokenExpires = New-Object Chilkat.CkDateTime
$success = $tokenExpires.SetFromCurrentSystemTime()
if ($success -ne $true) {
    $("Could not read time.")
    exit
}

$success = $http.HttpReq($tokenUrl.GetAsString(),$request,$response)
if ($success -ne $true) {
    $("Token exchange failed; inspect diagnostics privately.")
    exit
}

if ($response.StatusCode -ne 200) {
    $("Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.")
    exit
}

$success = $result.Load($response.BodyStr)
if ($success -ne $true) {
    $("Invalid JSON response.")
    exit
}

$stringCompare.SetString($result.StringOf("access_token"))
$stringMatch3 = $stringCompare.ContentsEqual("",$true)
if (($result.JsonTypeOf("access_token") -ne 1) -or ($stringMatch3 -eq $true)) {
    $("Missing or invalid access_token.")
    exit
}

$stringCompare.SetString($result.StringOf("token_type"))
$stringMatch4 = $stringCompare.ContentsEqual("Bearer",$true)
if ($stringMatch4 -ne $true) {
    $("Expected Bearer token.")
    exit
}

if (($result.JsonTypeOf("expires_in") -ne 2)) {
    $("Missing token lifetime.")
    exit
}

$validate7 = New-Object Chilkat.StringBuilder
$alphabet7 = New-Object Chilkat.StringBuilder
$success = $validate7.Append($result.StringOf("expires_in"))
if ($success -ne $true) {
    $("Could not validate token lifetime.")
    exit
}

$success = $alphabet7.Append("0123456789")
if ($success -ne $true) {
    $("Could not initialize validation.")
    exit
}

if (($validate7.Length -lt 1) -or ($validate7.Length -gt 8)) {
    $("Invalid token lifetime length.")
    exit
}

$charIndex7 = 0
while (($charIndex7 -lt $validate7.Length)) {
    if ($alphabet7.Contains($validate7.GetRange($charIndex7,1,$false),$true) -ne $true) {
        $("Invalid character in token lifetime.")
        exit
    }

    $charIndex7 = $charIndex7 + 1
}

$tokenLifetime = $result.IntOf("expires_in")
if (($tokenLifetime -le 60) -or ($tokenLifetime -gt 604800)) {
    $("Unexpected token lifetime.")
    exit
}

$success = $tokenExpires.AddSeconds($tokenLifetime)
if ($success -ne $true) {
    $("Could not calculate expiration.")
    exit
}

$tokenNow = New-Object Chilkat.CkDateTime
$success = $tokenNow.SetFromCurrentSystemTime()
if ($success -ne $true) {
    $("Could not read time.")
    exit
}

if ($tokenExpires.DiffSeconds($tokenNow) -le 60) {
    $("Token expired before it could be saved.")
    exit
}

$saved = New-Object Chilkat.JsonObject
$success = $saved.UpdateString("access_token",$result.StringOf("access_token"))
if ($success -ne $true) {
    $("Could not set access_token.")
    exit
}

$success = $saved.UpdateString("expires_at",$tokenExpires.GetAsTimestamp($false))
if ($success -ne $true) {
    $("Could not set expires_at.")
    exit
}

$success = $saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
if ($success -ne $true) {
    $("Could not save the private token file.")
    exit
}

$("Example completed.")