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

CkPerl
use chilkat();

$success = 0;

$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(1);
$success = $config->LoadFile("qa_data/azure/keyvault.json");
if ($success != 1) {
    print "Could not load private Key Vault configuration." . "\r\n";
    exit;
}

$stringCompare->SetString($config->stringOf("client_id"));
$stringMatch1 = $stringCompare->ContentsEqual("",1);
if (($config->JsonTypeOf("client_id") != 1) or ($stringMatch1 == 1)) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

$stringCompare->SetString($config->stringOf("tenant_id"));
$stringMatch2 = $stringCompare->ContentsEqual("",1);
if (($config->JsonTypeOf("tenant_id") != 1) or ($stringMatch2 == 1)) {
    print "Missing or invalid tenant_id." . "\r\n";
    exit;
}

$validate5 = chilkat::CkStringBuilder->new();
$alphabet5 = chilkat::CkStringBuilder->new();
$success = $validate5->Append($config->stringOf("tenant_id"));
if ($success != 1) {
    print "Could not validate tenant GUID." . "\r\n";
    exit;
}

$success = $alphabet5->Append("0123456789abcdefABCDEF-");
if ($success != 1) {
    print "Could not initialize validation." . "\r\n";
    exit;
}

if (($validate5->get_Length() < 36) or ($validate5->get_Length() > 36)) {
    print "Invalid tenant GUID length." . "\r\n";
    exit;
}

$charIndex5 = 0;
while (($charIndex5 < $validate5->get_Length())) {
    if ($alphabet5->Contains($validate5->getRange($charIndex5,1,0),1) != 1) {
        print "Invalid character in tenant GUID." . "\r\n";
        exit;
    }

    $charIndex5 = $charIndex5 + 1;
}

$http = chilkat::CkHttp->new();
$http->put_RequireSslCertVerify(1);
$http->put_FollowRedirects(0);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(60);
$http->put_VerboseLogging(0);
$request = chilkat::CkHttpRequest->new();
$request->put_HttpVerb("GET");
$response = chilkat::CkHttpResponse->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
$tokenUrl = chilkat::CkStringBuilder->new();
$success = $tokenUrl->Append("https://login.microsoftonline.com/");
if ($success != 1) {
    print "Could not construct URL or identifier." . "\r\n";
    exit;
}

$success = $tokenUrl->Append($config->stringOf("tenant_id"));
if ($success != 1) {
    print "Could not construct URL or identifier." . "\r\n";
    exit;
}

$success = $tokenUrl->Append("/oauth2/v2.0/token");
if ($success != 1) {
    print "Could not construct URL or identifier." . "\r\n";
    exit;
}

if ($config->JsonTypeOf("client_pfx_password") != 1) {
    print "Missing client_pfx_password string." . "\r\n";
    exit;
}

$clientCert = chilkat::CkCert->new();
$success = $clientCert->LoadPfxFile("qa_data/azure/client-auth.pfx",$config->stringOf("client_pfx_password"));
if ($success != 1) {
    print "Could not load client authentication PFX." . "\r\n";
    exit;
}

if ($clientCert->IsRsa() != 1) {
    print "PS256 client assertion requires RSA." . "\r\n";
    exit;
}

$signingKey = chilkat::CkPrivateKey->new();
$success = $clientCert->GetPrivateKey($signingKey);
if ($success != 1) {
    print "Client certificate needs a private key." . "\r\n";
    exit;
}

$certificateDer = chilkat::CkBinData->new();
$success = $certificateDer->AppendEncoded($clientCert->getEncoded(),"base64");
if ($success != 1) {
    print "Could not encode client certificate." . "\r\n";
    exit;
}

$thumbprint = $certificateDer->getHash("sha256","base64url");
if ($certificateDer->get_LastMethodSuccess() != 1) {
    print "Could not hash certificate." . "\r\n";
    exit;
}

$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() != 1) {
    print "Could not generate assertion ID." . "\r\n";
    exit;
}

$success = $header->UpdateString("alg","PS256");
if ($success != 1) {
    print "Could not set alg." . "\r\n";
    exit;
}

$success = $header->UpdateString("typ","JWT");
if ($success != 1) {
    print "Could not set typ." . "\r\n";
    exit;
}

$success = $header->UpdateString("x5t#S256",$thumbprint);
if ($success != 1) {
    print "Could not set x5t#S256." . "\r\n";
    exit;
}

$success = $claims->UpdateString("iss",$config->stringOf("client_id"));
if ($success != 1) {
    print "Could not set iss." . "\r\n";
    exit;
}

$success = $claims->UpdateString("sub",$config->stringOf("client_id"));
if ($success != 1) {
    print "Could not set sub." . "\r\n";
    exit;
}

$success = $claims->UpdateString("aud",$tokenUrl->getAsString());
if ($success != 1) {
    print "Could not set aud." . "\r\n";
    exit;
}

$success = $claims->UpdateString("jti",$jwtId);
if ($success != 1) {
    print "Could not set jti." . "\r\n";
    exit;
}

$success = $claims->UpdateInt("nbf",$jwt->GenNumericDate(-30));
if ($success != 1) {
    print "Could not set assertion start." . "\r\n";
    exit;
}

$success = $claims->UpdateInt("iat",$jwt->GenNumericDate(0));
if ($success != 1) {
    print "Could not set assertion issue time." . "\r\n";
    exit;
}

$success = $claims->UpdateInt("exp",$jwt->GenNumericDate(300));
if ($success != 1) {
    print "Could not set assertion expiration." . "\r\n";
    exit;
}

$assertion = $jwt->createJwtPk($header->emit(),$claims->emit(),$signingKey);
if ($jwt->get_LastMethodSuccess() != 1) {
    print "Could not sign the client assertion." . "\r\n";
    exit;
}

$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 != 1) {
    print "Could not read time." . "\r\n";
    exit;
}

$success = $http->HttpReq($tokenUrl->getAsString(),$request,$response);
if ($success != 1) {
    print "Token exchange failed; inspect diagnostics privately." . "\r\n";
    exit;
}

if ($response->get_StatusCode() != 200) {
    print "Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying." . "\r\n";
    exit;
}

$success = $result->Load($response->bodyStr());
if ($success != 1) {
    print "Invalid JSON response." . "\r\n";
    exit;
}

$stringCompare->SetString($result->stringOf("access_token"));
$stringMatch3 = $stringCompare->ContentsEqual("",1);
if (($result->JsonTypeOf("access_token") != 1) or ($stringMatch3 == 1)) {
    print "Missing or invalid access_token." . "\r\n";
    exit;
}

$stringCompare->SetString($result->stringOf("token_type"));
$stringMatch4 = $stringCompare->ContentsEqual("Bearer",1);
if ($stringMatch4 != 1) {
    print "Expected Bearer token." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("expires_in") != 2)) {
    print "Missing token lifetime." . "\r\n";
    exit;
}

$validate7 = chilkat::CkStringBuilder->new();
$alphabet7 = chilkat::CkStringBuilder->new();
$success = $validate7->Append($result->stringOf("expires_in"));
if ($success != 1) {
    print "Could not validate token lifetime." . "\r\n";
    exit;
}

$success = $alphabet7->Append("0123456789");
if ($success != 1) {
    print "Could not initialize validation." . "\r\n";
    exit;
}

if (($validate7->get_Length() < 1) or ($validate7->get_Length() > 8)) {
    print "Invalid token lifetime length." . "\r\n";
    exit;
}

$charIndex7 = 0;
while (($charIndex7 < $validate7->get_Length())) {
    if ($alphabet7->Contains($validate7->getRange($charIndex7,1,0),1) != 1) {
        print "Invalid character in token lifetime." . "\r\n";
        exit;
    }

    $charIndex7 = $charIndex7 + 1;
}

$tokenLifetime = $result->IntOf("expires_in");
if (($tokenLifetime <= 60) or ($tokenLifetime > 604800)) {
    print "Unexpected token lifetime." . "\r\n";
    exit;
}

$success = $tokenExpires->AddSeconds($tokenLifetime);
if ($success != 1) {
    print "Could not calculate expiration." . "\r\n";
    exit;
}

$tokenNow = chilkat::CkDateTime->new();
$success = $tokenNow->SetFromCurrentSystemTime();
if ($success != 1) {
    print "Could not read time." . "\r\n";
    exit;
}

if ($tokenExpires->DiffSeconds($tokenNow) <= 60) {
    print "Token expired before it could be saved." . "\r\n";
    exit;
}

$saved = chilkat::CkJsonObject->new();
$success = $saved->UpdateString("access_token",$result->stringOf("access_token"));
if ($success != 1) {
    print "Could not set access_token." . "\r\n";
    exit;
}

$success = $saved->UpdateString("expires_at",$tokenExpires->getAsTimestamp(0));
if ($success != 1) {
    print "Could not set expires_at." . "\r\n";
    exit;
}

$success = $saved->WriteFile("qa_data/tokens/azureKeyVaultToken.json");
if ($success != 1) {
    print "Could not save the private token file." . "\r\n";
    exit;
}

print "Example completed." . "\r\n";