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 CkJava Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
CkStringBuilder stringCompare = new CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
CkJsonObject config = new CkJsonObject();
config.put_Strict(true);
success = config.LoadFile("qa_data/azure/keyvault.json");
if (success != true) {
System.out.println("Could not load private Key Vault configuration.");
return;
}
stringCompare.SetString(config.stringOf("client_id"));
boolean stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("client_id") != 1) || (stringMatch1 == true)) {
System.out.println("Missing or invalid client_id.");
return;
}
stringCompare.SetString(config.stringOf("tenant_id"));
boolean stringMatch2 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("tenant_id") != 1) || (stringMatch2 == true)) {
System.out.println("Missing or invalid tenant_id.");
return;
}
CkStringBuilder validate5 = new CkStringBuilder();
CkStringBuilder alphabet5 = new CkStringBuilder();
success = validate5.Append(config.stringOf("tenant_id"));
if (success != true) {
System.out.println("Could not validate tenant GUID.");
return;
}
success = alphabet5.Append("0123456789abcdefABCDEF-");
if (success != true) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate5.get_Length() < 36) || (validate5.get_Length() > 36)) {
System.out.println("Invalid tenant GUID length.");
return;
}
int charIndex5 = 0;
while ((charIndex5 < validate5.get_Length())) {
if (alphabet5.Contains(validate5.getRange(charIndex5,1,false),true) != true) {
System.out.println("Invalid character in tenant GUID.");
return;
}
charIndex5 = charIndex5+1;
}
CkHttp http = new CkHttp();
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
http.put_VerboseLogging(false);
CkHttpRequest request = new CkHttpRequest();
request.put_HttpVerb("GET");
CkHttpResponse response = new CkHttpResponse();
CkJsonObject result = new CkJsonObject();
result.put_Strict(true);
CkStringBuilder tokenUrl = new CkStringBuilder();
success = tokenUrl.Append("https://login.microsoftonline.com/");
if (success != true) {
System.out.println("Could not construct URL or identifier.");
return;
}
success = tokenUrl.Append(config.stringOf("tenant_id"));
if (success != true) {
System.out.println("Could not construct URL or identifier.");
return;
}
success = tokenUrl.Append("/oauth2/v2.0/token");
if (success != true) {
System.out.println("Could not construct URL or identifier.");
return;
}
if (config.JsonTypeOf("client_pfx_password") != 1) {
System.out.println("Missing client_pfx_password string.");
return;
}
CkCert clientCert = new CkCert();
success = clientCert.LoadPfxFile("qa_data/azure/client-auth.pfx",config.stringOf("client_pfx_password"));
if (success != true) {
System.out.println("Could not load client authentication PFX.");
return;
}
if (clientCert.IsRsa() != true) {
System.out.println("PS256 client assertion requires RSA.");
return;
}
CkPrivateKey signingKey = new CkPrivateKey();
success = clientCert.GetPrivateKey(signingKey);
if (success != true) {
System.out.println("Client certificate needs a private key.");
return;
}
CkBinData certificateDer = new CkBinData();
success = certificateDer.AppendEncoded(clientCert.getEncoded(),"base64");
if (success != true) {
System.out.println("Could not encode client certificate.");
return;
}
String thumbprint = certificateDer.getHash("sha256","base64url");
if (certificateDer.get_LastMethodSuccess() != true) {
System.out.println("Could not hash certificate.");
return;
}
CkJsonObject header = new CkJsonObject();
CkJsonObject claims = new CkJsonObject();
CkJwt jwt = new CkJwt();
CkPrng random = new CkPrng();
String jwtId = random.genRandom(32,"hex");
if (random.get_LastMethodSuccess() != true) {
System.out.println("Could not generate assertion ID.");
return;
}
success = header.UpdateString("alg","PS256");
if (success != true) {
System.out.println("Could not set alg.");
return;
}
success = header.UpdateString("typ","JWT");
if (success != true) {
System.out.println("Could not set typ.");
return;
}
success = header.UpdateString("x5t#S256",thumbprint);
if (success != true) {
System.out.println("Could not set x5t#S256.");
return;
}
success = claims.UpdateString("iss",config.stringOf("client_id"));
if (success != true) {
System.out.println("Could not set iss.");
return;
}
success = claims.UpdateString("sub",config.stringOf("client_id"));
if (success != true) {
System.out.println("Could not set sub.");
return;
}
success = claims.UpdateString("aud",tokenUrl.getAsString());
if (success != true) {
System.out.println("Could not set aud.");
return;
}
success = claims.UpdateString("jti",jwtId);
if (success != true) {
System.out.println("Could not set jti.");
return;
}
success = claims.UpdateInt("nbf",jwt.GenNumericDate(-30));
if (success != true) {
System.out.println("Could not set assertion start.");
return;
}
success = claims.UpdateInt("iat",jwt.GenNumericDate(0));
if (success != true) {
System.out.println("Could not set assertion issue time.");
return;
}
success = claims.UpdateInt("exp",jwt.GenNumericDate(300));
if (success != true) {
System.out.println("Could not set assertion expiration.");
return;
}
String assertion = jwt.createJwtPk(header.emit(),claims.emit(),signingKey);
if (jwt.get_LastMethodSuccess() != true) {
System.out.println("Could not sign the client assertion.");
return;
}
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);
CkDateTime tokenExpires = new CkDateTime();
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
System.out.println("Could not read time.");
return;
}
success = http.HttpReq(tokenUrl.getAsString(),request,response);
if (success != true) {
System.out.println("Token exchange failed; inspect diagnostics privately.");
return;
}
if (response.get_StatusCode() != 200) {
System.out.println("Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
System.out.println("Invalid JSON response.");
return;
}
stringCompare.SetString(result.stringOf("access_token"));
boolean stringMatch3 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("access_token") != 1) || (stringMatch3 == true)) {
System.out.println("Missing or invalid access_token.");
return;
}
stringCompare.SetString(result.stringOf("token_type"));
boolean stringMatch4 = stringCompare.ContentsEqual("Bearer",true);
if (stringMatch4 != true) {
System.out.println("Expected Bearer token.");
return;
}
if ((result.JsonTypeOf("expires_in") != 2)) {
System.out.println("Missing token lifetime.");
return;
}
CkStringBuilder validate7 = new CkStringBuilder();
CkStringBuilder alphabet7 = new CkStringBuilder();
success = validate7.Append(result.stringOf("expires_in"));
if (success != true) {
System.out.println("Could not validate token lifetime.");
return;
}
success = alphabet7.Append("0123456789");
if (success != true) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate7.get_Length() < 1) || (validate7.get_Length() > 8)) {
System.out.println("Invalid token lifetime length.");
return;
}
int charIndex7 = 0;
while ((charIndex7 < validate7.get_Length())) {
if (alphabet7.Contains(validate7.getRange(charIndex7,1,false),true) != true) {
System.out.println("Invalid character in token lifetime.");
return;
}
charIndex7 = charIndex7+1;
}
int tokenLifetime = result.IntOf("expires_in");
if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
System.out.println("Unexpected token lifetime.");
return;
}
success = tokenExpires.AddSeconds(tokenLifetime);
if (success != true) {
System.out.println("Could not calculate expiration.");
return;
}
CkDateTime tokenNow = new CkDateTime();
success = tokenNow.SetFromCurrentSystemTime();
if (success != true) {
System.out.println("Could not read time.");
return;
}
if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
System.out.println("Token expired before it could be saved.");
return;
}
CkJsonObject saved = new CkJsonObject();
success = saved.UpdateString("access_token",result.stringOf("access_token"));
if (success != true) {
System.out.println("Could not set access_token.");
return;
}
success = saved.UpdateString("expires_at",tokenExpires.getAsTimestamp(false));
if (success != true) {
System.out.println("Could not set expires_at.");
return;
}
success = saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json");
if (success != true) {
System.out.println("Could not save the private token file.");
return;
}
System.out.println("Example completed.");
}
}