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.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkCertW.h>
#include <CkPrivateKeyW.h>
#include <CkBinDataW.h>
#include <CkJwtW.h>
#include <CkPrngW.h>
#include <CkDateTimeW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
CkJsonObjectW config;
config.put_Strict(true);
success = config.LoadFile(L"qa_data/azure/keyvault.json");
if (success != true) {
wprintf(L"Could not load private Key Vault configuration.\n");
return;
}
stringCompare.SetString(config.stringOf(L"client_id"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"client_id") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
stringCompare.SetString(config.stringOf(L"tenant_id"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"tenant_id") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid tenant_id.\n");
return;
}
CkStringBuilderW validate5;
CkStringBuilderW alphabet5;
success = validate5.Append(config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not validate tenant GUID.\n");
return;
}
success = alphabet5.Append(L"0123456789abcdefABCDEF-");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate5.get_Length() < 36) || (validate5.get_Length() > 36)) {
wprintf(L"Invalid tenant GUID length.\n");
return;
}
int charIndex5 = 0;
while ((charIndex5 < validate5.get_Length())) {
if (alphabet5.Contains(validate5.getRange(charIndex5,1,false),true) != true) {
wprintf(L"Invalid character in tenant GUID.\n");
return;
}
charIndex5 = charIndex5 + 1;
}
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
http.put_VerboseLogging(false);
CkHttpRequestW request;
request.put_HttpVerb(L"GET");
CkHttpResponseW response;
CkJsonObjectW result;
result.put_Strict(true);
CkStringBuilderW tokenUrl;
success = tokenUrl.Append(L"https://login.microsoftonline.com/");
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
success = tokenUrl.Append(config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
success = tokenUrl.Append(L"/oauth2/v2.0/token");
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
if (config.JsonTypeOf(L"client_pfx_password") != 1) {
wprintf(L"Missing client_pfx_password string.\n");
return;
}
CkCertW clientCert;
success = clientCert.LoadPfxFile(L"qa_data/azure/client-auth.pfx",config.stringOf(L"client_pfx_password"));
if (success != true) {
wprintf(L"Could not load client authentication PFX.\n");
return;
}
if (clientCert.IsRsa() != true) {
wprintf(L"PS256 client assertion requires RSA.\n");
return;
}
CkPrivateKeyW signingKey;
success = clientCert.GetPrivateKey(signingKey);
if (success != true) {
wprintf(L"Client certificate needs a private key.\n");
return;
}
CkBinDataW certificateDer;
success = certificateDer.AppendEncoded(clientCert.getEncoded(),L"base64");
if (success != true) {
wprintf(L"Could not encode client certificate.\n");
return;
}
const wchar_t *thumbprint = certificateDer.getHash(L"sha256",L"base64url");
if (certificateDer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash certificate.\n");
return;
}
CkJsonObjectW header;
CkJsonObjectW claims;
CkJwtW jwt;
CkPrngW random;
const wchar_t *jwtId = random.genRandom(32,L"hex");
if (random.get_LastMethodSuccess() != true) {
wprintf(L"Could not generate assertion ID.\n");
return;
}
success = header.UpdateString(L"alg",L"PS256");
if (success != true) {
wprintf(L"Could not set alg.\n");
return;
}
success = header.UpdateString(L"typ",L"JWT");
if (success != true) {
wprintf(L"Could not set typ.\n");
return;
}
success = header.UpdateString(L"x5t#S256",thumbprint);
if (success != true) {
wprintf(L"Could not set x5t#S256.\n");
return;
}
success = claims.UpdateString(L"iss",config.stringOf(L"client_id"));
if (success != true) {
wprintf(L"Could not set iss.\n");
return;
}
success = claims.UpdateString(L"sub",config.stringOf(L"client_id"));
if (success != true) {
wprintf(L"Could not set sub.\n");
return;
}
success = claims.UpdateString(L"aud",tokenUrl.getAsString());
if (success != true) {
wprintf(L"Could not set aud.\n");
return;
}
success = claims.UpdateString(L"jti",jwtId);
if (success != true) {
wprintf(L"Could not set jti.\n");
return;
}
success = claims.UpdateInt(L"nbf",jwt.GenNumericDate(-30));
if (success != true) {
wprintf(L"Could not set assertion start.\n");
return;
}
success = claims.UpdateInt(L"iat",jwt.GenNumericDate(0));
if (success != true) {
wprintf(L"Could not set assertion issue time.\n");
return;
}
success = claims.UpdateInt(L"exp",jwt.GenNumericDate(300));
if (success != true) {
wprintf(L"Could not set assertion expiration.\n");
return;
}
const wchar_t *assertion = jwt.createJwtPk(header.emit(),claims.emit(),signingKey);
if (jwt.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign the client assertion.\n");
return;
}
request.put_HttpVerb(L"POST");
request.put_ContentType(L"application/x-www-form-urlencoded");
request.AddParam(L"client_id",config.stringOf(L"client_id"));
request.AddParam(L"scope",L"https://vault.azure.net/.default");
request.AddParam(L"grant_type",L"client_credentials");
request.AddParam(L"client_assertion_type",L"urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
request.AddParam(L"client_assertion",assertion);
CkDateTimeW tokenExpires;
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read time.\n");
return;
}
success = http.HttpReq(tokenUrl.getAsString(),request,response);
if (success != true) {
wprintf(L"Token exchange failed; inspect diagnostics privately.\n");
return;
}
if (response.get_StatusCode() != 200) {
wprintf(L"Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Invalid JSON response.\n");
return;
}
stringCompare.SetString(result.stringOf(L"access_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"access_token") != 1) || (stringMatch3 == true)) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
stringCompare.SetString(result.stringOf(L"token_type"));
bool stringMatch4 = stringCompare.ContentsEqual(L"Bearer",true);
if (stringMatch4 != true) {
wprintf(L"Expected Bearer token.\n");
return;
}
if ((result.JsonTypeOf(L"expires_in") != 2)) {
wprintf(L"Missing token lifetime.\n");
return;
}
CkStringBuilderW validate7;
CkStringBuilderW alphabet7;
success = validate7.Append(result.stringOf(L"expires_in"));
if (success != true) {
wprintf(L"Could not validate token lifetime.\n");
return;
}
success = alphabet7.Append(L"0123456789");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate7.get_Length() < 1) || (validate7.get_Length() > 8)) {
wprintf(L"Invalid token lifetime length.\n");
return;
}
int charIndex7 = 0;
while ((charIndex7 < validate7.get_Length())) {
if (alphabet7.Contains(validate7.getRange(charIndex7,1,false),true) != true) {
wprintf(L"Invalid character in token lifetime.\n");
return;
}
charIndex7 = charIndex7 + 1;
}
int tokenLifetime = result.IntOf(L"expires_in");
if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
wprintf(L"Unexpected token lifetime.\n");
return;
}
success = tokenExpires.AddSeconds(tokenLifetime);
if (success != true) {
wprintf(L"Could not calculate expiration.\n");
return;
}
CkDateTimeW tokenNow;
success = tokenNow.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read time.\n");
return;
}
if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
wprintf(L"Token expired before it could be saved.\n");
return;
}
CkJsonObjectW saved;
success = saved.UpdateString(L"access_token",result.stringOf(L"access_token"));
if (success != true) {
wprintf(L"Could not set access_token.\n");
return;
}
success = saved.UpdateString(L"expires_at",tokenExpires.getAsTimestamp(false));
if (success != true) {
wprintf(L"Could not set expires_at.\n");
return;
}
success = saved.WriteFile(L"qa_data/tokens/azureKeyVaultToken.json");
if (success != true) {
wprintf(L"Could not save the private token file.\n");
return;
}
wprintf(L"Example completed.\n");
}