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

Ruby
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

if (config.JsonTypeOf("client_pfx_password") != 1)
    print "Missing client_pfx_password string." + "\n";
    exit
end

clientCert = Chilkat::CkCert.new()
success = clientCert.LoadPfxFile("qa_data/azure/client-auth.pfx",config.stringOf("client_pfx_password"))
if (success != true)
    print "Could not load client authentication PFX." + "\n";
    exit
end

if (clientCert.IsRsa() != true)
    print "PS256 client assertion requires RSA." + "\n";
    exit
end

signingKey = Chilkat::CkPrivateKey.new()
success = clientCert.GetPrivateKey(signingKey)
if (success != true)
    print "Client certificate needs a private key." + "\n";
    exit
end

certificateDer = Chilkat::CkBinData.new()
success = certificateDer.AppendEncoded(clientCert.getEncoded(),"base64")
if (success != true)
    print "Could not encode client certificate." + "\n";
    exit
end

thumbprint = certificateDer.getHash("sha256","base64url")
if (certificateDer.get_LastMethodSuccess() != true)
    print "Could not hash certificate." + "\n";
    exit
end

header = Chilkat::CkJsonObject.new()
claims = Chilkat::CkJsonObject.new()
jwt = Chilkat::CkJwt.new()
random = Chilkat::CkPrng.new()
jwtId = random.genRandom(32,"hex")
if (random.get_LastMethodSuccess() != true)
    print "Could not generate assertion ID." + "\n";
    exit
end

success = header.UpdateString("alg","PS256")
if (success != true)
    print "Could not set alg." + "\n";
    exit
end

success = header.UpdateString("typ","JWT")
if (success != true)
    print "Could not set typ." + "\n";
    exit
end

success = header.UpdateString("x5t#S256",thumbprint)
if (success != true)
    print "Could not set x5t#S256." + "\n";
    exit
end

success = claims.UpdateString("iss",config.stringOf("client_id"))
if (success != true)
    print "Could not set iss." + "\n";
    exit
end

success = claims.UpdateString("sub",config.stringOf("client_id"))
if (success != true)
    print "Could not set sub." + "\n";
    exit
end

success = claims.UpdateString("aud",tokenUrl.getAsString())
if (success != true)
    print "Could not set aud." + "\n";
    exit
end

success = claims.UpdateString("jti",jwtId)
if (success != true)
    print "Could not set jti." + "\n";
    exit
end

success = claims.UpdateInt("nbf",jwt.GenNumericDate(-30))
if (success != true)
    print "Could not set assertion start." + "\n";
    exit
end

success = claims.UpdateInt("iat",jwt.GenNumericDate(0))
if (success != true)
    print "Could not set assertion issue time." + "\n";
    exit
end

success = claims.UpdateInt("exp",jwt.GenNumericDate(300))
if (success != true)
    print "Could not set assertion expiration." + "\n";
    exit
end

assertion = jwt.createJwtPk(header.emit(),claims.emit(),signingKey)
if (jwt.get_LastMethodSuccess() != true)
    print "Could not sign the client assertion." + "\n";
    exit
end

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

validate7 = Chilkat::CkStringBuilder.new()
alphabet7 = Chilkat::CkStringBuilder.new()
success = validate7.Append(result.stringOf("expires_in"))
if (success != true)
    print "Could not validate token lifetime." + "\n";
    exit
end

success = alphabet7.Append("0123456789")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate7.get_Length() < 1) or (validate7.get_Length() > 8))
    print "Invalid token lifetime length." + "\n";
    exit
end

charIndex7 = 0
while (charIndex7 < validate7.get_Length())
    if (alphabet7.Contains(validate7.getRange(charIndex7,1,false),true) != true)
        print "Invalid character in token lifetime." + "\n";
        exit
    end

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