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

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
config: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
validate5: HCkStringBuilder;
alphabet5: HCkStringBuilder;
charIndex5: Integer;
http: HCkHttp;
request: HCkHttpRequest;
response: HCkHttpResponse;
result: HCkJsonObject;
tokenUrl: HCkStringBuilder;
clientCert: HCkCert;
signingKey: HCkPrivateKey;
certificateDer: HCkBinData;
thumbprint: PWideChar;
header: HCkJsonObject;
claims: HCkJsonObject;
jwt: HCkJwt;
random: HCkPrng;
jwtId: PWideChar;
assertion: PWideChar;
tokenExpires: HCkDateTime;
stringMatch3: Boolean;
stringMatch4: Boolean;
validate7: HCkStringBuilder;
alphabet7: HCkStringBuilder;
charIndex7: Integer;
tokenLifetime: Integer;
tokenNow: HCkDateTime;
saved: HCkJsonObject;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this configuration private, outside public web content and source control.
config := CkJsonObject_Create();
CkJsonObject_putStrict(config,True);
success := CkJsonObject_LoadFile(config,'qa_data/azure/keyvault.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private Key Vault configuration.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'client_id'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'client_id') <> 1) or (stringMatch1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'tenant_id'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'tenant_id') <> 1) or (stringMatch2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid tenant_id.');
    Exit;
  end;
validate5 := CkStringBuilder_Create();
alphabet5 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate5,CkJsonObject__stringOf(config,'tenant_id'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not validate tenant GUID.');
    Exit;
  end;
success := CkStringBuilder_Append(alphabet5,'0123456789abcdefABCDEF-');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not initialize validation.');
    Exit;
  end;
if ((CkStringBuilder_getLength(validate5) < 36) or (CkStringBuilder_getLength(validate5) > 36)) then
  begin
    Memo1.Lines.Add('Invalid tenant GUID length.');
    Exit;
  end;
charIndex5 := 0;
while (charIndex5 < CkStringBuilder_getLength(validate5)) do
  begin
    if (CkStringBuilder_Contains(alphabet5,CkStringBuilder__getRange(validate5,charIndex5,1,False),True) <> True) then
      begin
        Memo1.Lines.Add('Invalid character in tenant GUID.');
        Exit;
      end;
    charIndex5 := charIndex5 + 1;
  end;

http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
CkHttp_putVerboseLogging(http,False);
request := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(request,'GET');
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
tokenUrl := CkStringBuilder_Create();
success := CkStringBuilder_Append(tokenUrl,'https://login.microsoftonline.com/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(tokenUrl,CkJsonObject__stringOf(config,'tenant_id'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
success := CkStringBuilder_Append(tokenUrl,'/oauth2/v2.0/token');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct URL or identifier.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(config,'client_pfx_password') <> 1) then
  begin
    Memo1.Lines.Add('Missing client_pfx_password string.');
    Exit;
  end;
clientCert := CkCert_Create();
success := CkCert_LoadPfxFile(clientCert,'qa_data/azure/client-auth.pfx',CkJsonObject__stringOf(config,'client_pfx_password'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load client authentication PFX.');
    Exit;
  end;
if (CkCert_IsRsa(clientCert) <> True) then
  begin
    Memo1.Lines.Add('PS256 client assertion requires RSA.');
    Exit;
  end;
signingKey := CkPrivateKey_Create();
success := CkCert_GetPrivateKey(clientCert,signingKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Client certificate needs a private key.');
    Exit;
  end;
certificateDer := CkBinData_Create();
success := CkBinData_AppendEncoded(certificateDer,CkCert__getEncoded(clientCert),'base64');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode client certificate.');
    Exit;
  end;
thumbprint := CkBinData__getHash(certificateDer,'sha256','base64url');
if (CkBinData_getLastMethodSuccess(certificateDer) <> True) then
  begin
    Memo1.Lines.Add('Could not hash certificate.');
    Exit;
  end;
header := CkJsonObject_Create();
claims := CkJsonObject_Create();
jwt := CkJwt_Create();
random := CkPrng_Create();
jwtId := CkPrng__genRandom(random,32,'hex');
if (CkPrng_getLastMethodSuccess(random) <> True) then
  begin
    Memo1.Lines.Add('Could not generate assertion ID.');
    Exit;
  end;
success := CkJsonObject_UpdateString(header,'alg','PS256');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set alg.');
    Exit;
  end;
success := CkJsonObject_UpdateString(header,'typ','JWT');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set typ.');
    Exit;
  end;
success := CkJsonObject_UpdateString(header,'x5t#S256',thumbprint);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set x5t#S256.');
    Exit;
  end;
success := CkJsonObject_UpdateString(claims,'iss',CkJsonObject__stringOf(config,'client_id'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set iss.');
    Exit;
  end;
success := CkJsonObject_UpdateString(claims,'sub',CkJsonObject__stringOf(config,'client_id'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set sub.');
    Exit;
  end;
success := CkJsonObject_UpdateString(claims,'aud',CkStringBuilder__getAsString(tokenUrl));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set aud.');
    Exit;
  end;
success := CkJsonObject_UpdateString(claims,'jti',jwtId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set jti.');
    Exit;
  end;
success := CkJsonObject_UpdateInt(claims,'nbf',CkJwt_GenNumericDate(jwt,-30));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set assertion start.');
    Exit;
  end;
success := CkJsonObject_UpdateInt(claims,'iat',CkJwt_GenNumericDate(jwt,0));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set assertion issue time.');
    Exit;
  end;
success := CkJsonObject_UpdateInt(claims,'exp',CkJwt_GenNumericDate(jwt,300));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set assertion expiration.');
    Exit;
  end;
assertion := CkJwt__createJwtPk(jwt,CkJsonObject__emit(header),CkJsonObject__emit(claims),signingKey);
if (CkJwt_getLastMethodSuccess(jwt) <> True) then
  begin
    Memo1.Lines.Add('Could not sign the client assertion.');
    Exit;
  end;
CkHttpRequest_putHttpVerb(request,'POST');
CkHttpRequest_putContentType(request,'application/x-www-form-urlencoded');
CkHttpRequest_AddParam(request,'client_id',CkJsonObject__stringOf(config,'client_id'));
CkHttpRequest_AddParam(request,'scope','https://vault.azure.net/.default');
CkHttpRequest_AddParam(request,'grant_type','client_credentials');
CkHttpRequest_AddParam(request,'client_assertion_type','urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
CkHttpRequest_AddParam(request,'client_assertion',assertion);
tokenExpires := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(tokenExpires);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read time.');
    Exit;
  end;
success := CkHttp_HttpReq(http,CkStringBuilder__getAsString(tokenUrl),request,response);
if (success <> True) then
  begin
    Memo1.Lines.Add('Token exchange failed; inspect diagnostics privately.');
    Exit;
  end;
if (CkHttpResponse_getStatusCode(response) <> 200) then
  begin
    Memo1.Lines.Add('Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid JSON response.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'access_token'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'access_token') <> 1) or (stringMatch3 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_token.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'token_type'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'Bearer',True);
if (stringMatch4 <> True) then
  begin
    Memo1.Lines.Add('Expected Bearer token.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(result,'expires_in') <> 2)) then
  begin
    Memo1.Lines.Add('Missing token lifetime.');
    Exit;
  end;
validate7 := CkStringBuilder_Create();
alphabet7 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate7,CkJsonObject__stringOf(result,'expires_in'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not validate token lifetime.');
    Exit;
  end;
success := CkStringBuilder_Append(alphabet7,'0123456789');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not initialize validation.');
    Exit;
  end;
if ((CkStringBuilder_getLength(validate7) < 1) or (CkStringBuilder_getLength(validate7) > 8)) then
  begin
    Memo1.Lines.Add('Invalid token lifetime length.');
    Exit;
  end;
charIndex7 := 0;
while (charIndex7 < CkStringBuilder_getLength(validate7)) do
  begin
    if (CkStringBuilder_Contains(alphabet7,CkStringBuilder__getRange(validate7,charIndex7,1,False),True) <> True) then
      begin
        Memo1.Lines.Add('Invalid character in token lifetime.');
        Exit;
      end;
    charIndex7 := charIndex7 + 1;
  end;

tokenLifetime := CkJsonObject_IntOf(result,'expires_in');
if ((tokenLifetime <= 60) or (tokenLifetime > 604800)) then
  begin
    Memo1.Lines.Add('Unexpected token lifetime.');
    Exit;
  end;
success := CkDateTime_AddSeconds(tokenExpires,tokenLifetime);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not calculate expiration.');
    Exit;
  end;
tokenNow := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(tokenNow);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read time.');
    Exit;
  end;
if (CkDateTime_DiffSeconds(tokenExpires,tokenNow) <= 60) then
  begin
    Memo1.Lines.Add('Token expired before it could be saved.');
    Exit;
  end;
saved := CkJsonObject_Create();
success := CkJsonObject_UpdateString(saved,'access_token',CkJsonObject__stringOf(result,'access_token'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set access_token.');
    Exit;
  end;
success := CkJsonObject_UpdateString(saved,'expires_at',CkDateTime__getAsTimestamp(tokenExpires,False));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set expires_at.');
    Exit;
  end;
success := CkJsonObject_WriteFile(saved,'qa_data/tokens/azureKeyVaultToken.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the private token file.');
    Exit;
  end;
Memo1.Lines.Add('Example completed.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(config);
CkStringBuilder_Dispose(validate5);
CkStringBuilder_Dispose(alphabet5);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(request);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkStringBuilder_Dispose(tokenUrl);
CkCert_Dispose(clientCert);
CkPrivateKey_Dispose(signingKey);
CkBinData_Dispose(certificateDer);
CkJsonObject_Dispose(header);
CkJsonObject_Dispose(claims);
CkJwt_Dispose(jwt);
CkPrng_Dispose(random);
CkDateTime_Dispose(tokenExpires);
CkStringBuilder_Dispose(validate7);
CkStringBuilder_Dispose(alphabet7);
CkDateTime_Dispose(tokenNow);
CkJsonObject_Dispose(saved);