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 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;
}
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;
// Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
http.UseIEProxy = false;
http.ProxyDomain = "";
http.ConnectTimeout = 5;
request.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"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("managed_identity_client_id") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid managed_identity_client_id.");
return;
}
request.AddParam("client_id",config.StringOf("managed_identity_client_id"));
}
Chilkat.CkDateTime tokenExpires = new Chilkat.CkDateTime();
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read time.");
return;
}
success = http.HttpReq("http://169.254.169.254/metadata/identity/oauth2/token",request,response);
if (success != true) {
Debug.WriteLine("IMDS request failed; run on an Azure VM with managed identity enabled.");
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 stringMatch2 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("access_token") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid access_token.");
return;
}
stringCompare.SetString(result.StringOf("token_type"));
bool stringMatch3 = stringCompare.ContentsEqual("Bearer",true);
if (stringMatch3 != true) {
Debug.WriteLine("Expected Bearer token.");
return;
}
if ((result.JsonTypeOf("expires_in") != 2) && (result.JsonTypeOf("expires_in") != 1)) {
Debug.WriteLine("Missing token lifetime.");
return;
}
Chilkat.StringBuilder validate6 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet6 = new Chilkat.StringBuilder();
success = validate6.Append(result.StringOf("expires_in"));
if (success != true) {
Debug.WriteLine("Could not validate token lifetime.");
return;
}
success = alphabet6.Append("0123456789");
if (success != true) {
Debug.WriteLine("Could not initialize validation.");
return;
}
if ((validate6.Length < 1) || (validate6.Length > 8)) {
Debug.WriteLine("Invalid token lifetime length.");
return;
}
int charIndex6 = 0;
while ((charIndex6 < validate6.Length)) {
if (alphabet6.Contains(validate6.GetRange(charIndex6,1,false),true) != true) {
Debug.WriteLine("Invalid character in token lifetime.");
return;
}
charIndex6 = charIndex6 + 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.");