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 .NET Core C# Downloads
bool success = false;
Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
Chilkat.JsonObject config = new Chilkat.JsonObject();
config.Strict = true;
success = config.LoadFile("qa_data/azure/keyvault.json");
if (success != true) {
Debug.WriteLine("Could not load private Key Vault configuration.");
return;
}
stringCompare.SetString(config.StringOf("client_id"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("client_id") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid client_id.");
return;
}
stringCompare.SetString(config.StringOf("tenant_id"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("tenant_id") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid tenant_id.");
return;
}
Chilkat.StringBuilder validate5 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet5 = new Chilkat.StringBuilder();
success = validate5.Append(config.StringOf("tenant_id"));
if (success != true) {
Debug.WriteLine("Could not validate tenant GUID.");
return;
}
success = alphabet5.Append("0123456789abcdefABCDEF-");
if (success != true) {
Debug.WriteLine("Could not initialize validation.");
return;
}
if ((validate5.Length < 36) || (validate5.Length > 36)) {
Debug.WriteLine("Invalid tenant GUID length.");
return;
}
int charIndex5 = 0;
while ((charIndex5 < validate5.Length)) {
if (alphabet5.Contains(validate5.GetRange(charIndex5,1,false),true) != true) {
Debug.WriteLine("Invalid character in tenant GUID.");
return;
}
charIndex5 = charIndex5 + 1;
}
Chilkat.Http http = new Chilkat.Http();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
http.ConnectTimeout = 20;
http.ReadTimeout = 60;
http.VerboseLogging = false;
Chilkat.HttpRequest request = new Chilkat.HttpRequest();
request.HttpVerb = "GET";
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
Chilkat.JsonObject result = new Chilkat.JsonObject();
result.Strict = true;
Chilkat.StringBuilder tokenUrl = new Chilkat.StringBuilder();
success = tokenUrl.Append("https://login.microsoftonline.com/");
if (success != true) {
Debug.WriteLine("Could not construct URL or identifier.");
return;
}
success = tokenUrl.Append(config.StringOf("tenant_id"));
if (success != true) {
Debug.WriteLine("Could not construct URL or identifier.");
return;
}
success = tokenUrl.Append("/oauth2/v2.0/token");
if (success != true) {
Debug.WriteLine("Could not construct URL or identifier.");
return;
}
if (config.JsonTypeOf("client_pfx_password") != 1) {
Debug.WriteLine("Missing client_pfx_password string.");
return;
}
Chilkat.Cert clientCert = new Chilkat.Cert();
success = clientCert.LoadPfxFile("qa_data/azure/client-auth.pfx",config.StringOf("client_pfx_password"));
if (success != true) {
Debug.WriteLine("Could not load client authentication PFX.");
return;
}
if (clientCert.IsRsa() != true) {
Debug.WriteLine("PS256 client assertion requires RSA.");
return;
}
Chilkat.PrivateKey signingKey = new Chilkat.PrivateKey();
success = clientCert.GetPrivateKey(signingKey);
if (success != true) {
Debug.WriteLine("Client certificate needs a private key.");
return;
}
Chilkat.BinData certificateDer = new Chilkat.BinData();
success = certificateDer.AppendEncoded(clientCert.GetEncoded(),"base64");
if (success != true) {
Debug.WriteLine("Could not encode client certificate.");
return;
}
string thumbprint = certificateDer.GetHash("sha256","base64url");
if (certificateDer.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash certificate.");
return;
}
Chilkat.JsonObject header = new Chilkat.JsonObject();
Chilkat.JsonObject claims = new Chilkat.JsonObject();
Chilkat.Jwt jwt = new Chilkat.Jwt();
Chilkat.Prng random = new Chilkat.Prng();
string jwtId = random.GenRandom(32,"hex");
if (random.LastMethodSuccess != true) {
Debug.WriteLine("Could not generate assertion ID.");
return;
}
success = header.UpdateString("alg","PS256");
if (success != true) {
Debug.WriteLine("Could not set alg.");
return;
}
success = header.UpdateString("typ","JWT");
if (success != true) {
Debug.WriteLine("Could not set typ.");
return;
}
success = header.UpdateString("x5t#S256",thumbprint);
if (success != true) {
Debug.WriteLine("Could not set x5t#S256.");
return;
}
success = claims.UpdateString("iss",config.StringOf("client_id"));
if (success != true) {
Debug.WriteLine("Could not set iss.");
return;
}
success = claims.UpdateString("sub",config.StringOf("client_id"));
if (success != true) {
Debug.WriteLine("Could not set sub.");
return;
}
success = claims.UpdateString("aud",tokenUrl.GetAsString());
if (success != true) {
Debug.WriteLine("Could not set aud.");
return;
}
success = claims.UpdateString("jti",jwtId);
if (success != true) {
Debug.WriteLine("Could not set jti.");
return;
}
success = claims.UpdateInt("nbf",jwt.GenNumericDate(-30));
if (success != true) {
Debug.WriteLine("Could not set assertion start.");
return;
}
success = claims.UpdateInt("iat",jwt.GenNumericDate(0));
if (success != true) {
Debug.WriteLine("Could not set assertion issue time.");
return;
}
success = claims.UpdateInt("exp",jwt.GenNumericDate(300));
if (success != true) {
Debug.WriteLine("Could not set assertion expiration.");
return;
}
string assertion = jwt.CreateJwtPk(header.Emit(),claims.Emit(),signingKey);
if (jwt.LastMethodSuccess != true) {
Debug.WriteLine("Could not sign the client assertion.");
return;
}
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);
Chilkat.CkDateTime tokenExpires = new Chilkat.CkDateTime();
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read time.");
return;
}
success = http.HttpReq(tokenUrl.GetAsString(),request,response);
if (success != true) {
Debug.WriteLine("Token exchange failed; inspect diagnostics privately.");
return;
}
if (response.StatusCode != 200) {
Debug.WriteLine("Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.");
return;
}
success = result.Load(response.BodyStr);
if (success != true) {
Debug.WriteLine("Invalid JSON response.");
return;
}
stringCompare.SetString(result.StringOf("access_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("access_token") != 1) || (stringMatch3 == true)) {
Debug.WriteLine("Missing or invalid access_token.");
return;
}
stringCompare.SetString(result.StringOf("token_type"));
bool stringMatch4 = stringCompare.ContentsEqual("Bearer",true);
if (stringMatch4 != true) {
Debug.WriteLine("Expected Bearer token.");
return;
}
if ((result.JsonTypeOf("expires_in") != 2)) {
Debug.WriteLine("Missing token lifetime.");
return;
}
Chilkat.StringBuilder validate7 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet7 = new Chilkat.StringBuilder();
success = validate7.Append(result.StringOf("expires_in"));
if (success != true) {
Debug.WriteLine("Could not validate token lifetime.");
return;
}
success = alphabet7.Append("0123456789");
if (success != true) {
Debug.WriteLine("Could not initialize validation.");
return;
}
if ((validate7.Length < 1) || (validate7.Length > 8)) {
Debug.WriteLine("Invalid token lifetime length.");
return;
}
int charIndex7 = 0;
while ((charIndex7 < validate7.Length)) {
if (alphabet7.Contains(validate7.GetRange(charIndex7,1,false),true) != true) {
Debug.WriteLine("Invalid character in token lifetime.");
return;
}
charIndex7 = charIndex7 + 1;
}
int tokenLifetime = result.IntOf("expires_in");
if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
Debug.WriteLine("Unexpected token lifetime.");
return;
}
success = tokenExpires.AddSeconds(tokenLifetime);
if (success != true) {
Debug.WriteLine("Could not calculate expiration.");
return;
}
Chilkat.CkDateTime tokenNow = new Chilkat.CkDateTime();
success = tokenNow.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read time.");
return;
}
if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
Debug.WriteLine("Token expired before it could be saved.");
return;
}
Chilkat.JsonObject saved = new Chilkat.JsonObject();
success = saved.UpdateString("access_token",result.StringOf("access_token"));
if (success != true) {
Debug.WriteLine("Could not set access_token.");
return;
}
success = saved.UpdateString("expires_at",tokenExpires.GetAsTimestamp(false));
if (success != true) {
Debug.WriteLine("Could not set expires_at.");
return;
}
success = saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json");
if (success != true) {
Debug.WriteLine("Could not save the private token file.");
return;
}
Debug.WriteLine("Example completed.");