Azure Key Vault: Get a Token with Azure VM Managed Identity
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.
Run on an Azure VM with an enabled system-assigned identity, or set managed_identity_client_id for an attached user-assigned identity. The fixed link-local endpoint and Metadata header are specific to VM IMDS, not App Service. Proxying and redirects are disabled. Grant the identity appropriate vault data-plane permissions. Saves the same private token format as the other examples; does not print tokens. The example stops on IMDS errors; production IMDS retries must follow its service-specific guidance.
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;
}
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);
// Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
http.put_UseIEProxy(false);
http.put_ProxyDomain("");
http.put_ConnectTimeout(5);
request.put_HttpVerb("GET");
request.AddHeader("Metadata","true");
request.AddParam("api-version","2018-02-01");
request.AddParam("resource","https://vault.azure.net");
if (config.HasMember("managed_identity_client_id") == true) {
stringCompare.SetString(config.stringOf("managed_identity_client_id"));
boolean stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("managed_identity_client_id") != 1) || (stringMatch1 == true)) {
System.out.println("Missing or invalid managed_identity_client_id.");
return;
}
request.AddParam("client_id",config.stringOf("managed_identity_client_id"));
}
CkDateTime tokenExpires = new CkDateTime();
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
System.out.println("Could not read time.");
return;
}
success = http.HttpReq("http://169.254.169.254/metadata/identity/oauth2/token",request,response);
if (success != true) {
System.out.println("IMDS request failed; run on an Azure VM with managed identity enabled.");
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 stringMatch2 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("access_token") != 1) || (stringMatch2 == true)) {
System.out.println("Missing or invalid access_token.");
return;
}
stringCompare.SetString(result.stringOf("token_type"));
boolean stringMatch3 = stringCompare.ContentsEqual("Bearer",true);
if (stringMatch3 != true) {
System.out.println("Expected Bearer token.");
return;
}
if ((result.JsonTypeOf("expires_in") != 2) && (result.JsonTypeOf("expires_in") != 1)) {
System.out.println("Missing token lifetime.");
return;
}
CkStringBuilder validate6 = new CkStringBuilder();
CkStringBuilder alphabet6 = new CkStringBuilder();
success = validate6.Append(result.stringOf("expires_in"));
if (success != true) {
System.out.println("Could not validate token lifetime.");
return;
}
success = alphabet6.Append("0123456789");
if (success != true) {
System.out.println("Could not initialize validation.");
return;
}
if ((validate6.get_Length() < 1) || (validate6.get_Length() > 8)) {
System.out.println("Invalid token lifetime length.");
return;
}
int charIndex6 = 0;
while ((charIndex6 < validate6.get_Length())) {
if (alphabet6.Contains(validate6.getRange(charIndex6,1,false),true) != true) {
System.out.println("Invalid character in token lifetime.");
return;
}
charIndex6 = charIndex6+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.");
}
}