Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

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.

Microsoft reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this configuration private, outside public web content and source control.
config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("qa_data/azure/keyvault.json")
if (success != true)
    print "Could not load private Key Vault configuration." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(60)
http.put_VerboseLogging(false)
request = Chilkat::CkHttpRequest.new()
request.put_HttpVerb("GET")
response = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
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"))
    stringMatch1 = stringCompare.ContentsEqual("",true)
    if ((config.JsonTypeOf("managed_identity_client_id") != 1) or (stringMatch1 == true))
        print "Missing or invalid managed_identity_client_id." + "\n";
        exit
    end

    request.AddParam("client_id",config.stringOf("managed_identity_client_id"))
end

tokenExpires = Chilkat::CkDateTime.new()
success = tokenExpires.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read time." + "\n";
    exit
end

success = http.HttpReq("http://169.254.169.254/metadata/identity/oauth2/token",request,response)
if (success != true)
    print "IMDS request failed; run on an Azure VM with managed identity enabled." + "\n";
    exit
end

if (response.get_StatusCode() != 200)
    print "Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying." + "\n";
    exit
end

success = result.Load(response.bodyStr())
if (success != true)
    print "Invalid JSON response." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("access_token"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("access_token") != 1) or (stringMatch2 == true))
    print "Missing or invalid access_token." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("token_type"))
stringMatch3 = stringCompare.ContentsEqual("Bearer",true)
if (stringMatch3 != true)
    print "Expected Bearer token." + "\n";
    exit
end

if ((result.JsonTypeOf("expires_in") != 2) and (result.JsonTypeOf("expires_in") != 1))
    print "Missing token lifetime." + "\n";
    exit
end

validate6 = Chilkat::CkStringBuilder.new()
alphabet6 = Chilkat::CkStringBuilder.new()
success = validate6.Append(result.stringOf("expires_in"))
if (success != true)
    print "Could not validate token lifetime." + "\n";
    exit
end

success = alphabet6.Append("0123456789")
if (success != true)
    print "Could not initialize validation." + "\n";
    exit
end

if ((validate6.get_Length() < 1) or (validate6.get_Length() > 8))
    print "Invalid token lifetime length." + "\n";
    exit
end

charIndex6 = 0
while (charIndex6 < validate6.get_Length())
    if (alphabet6.Contains(validate6.getRange(charIndex6,1,false),true) != true)
        print "Invalid character in token lifetime." + "\n";
        exit
    end

    charIndex6 = charIndex6 + 1
end
tokenLifetime = result.IntOf("expires_in")
if ((tokenLifetime <= 60) or (tokenLifetime > 604800))
    print "Unexpected token lifetime." + "\n";
    exit
end

success = tokenExpires.AddSeconds(tokenLifetime)
if (success != true)
    print "Could not calculate expiration." + "\n";
    exit
end

tokenNow = Chilkat::CkDateTime.new()
success = tokenNow.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read time." + "\n";
    exit
end

if (tokenExpires.DiffSeconds(tokenNow) <= 60)
    print "Token expired before it could be saved." + "\n";
    exit
end

saved = Chilkat::CkJsonObject.new()
success = saved.UpdateString("access_token",result.stringOf("access_token"))
if (success != true)
    print "Could not set access_token." + "\n";
    exit
end

success = saved.UpdateString("expires_at",tokenExpires.getAsTimestamp(false))
if (success != true)
    print "Could not set expires_at." + "\n";
    exit
end

success = saved.WriteFile("qa_data/tokens/azureKeyVaultToken.json")
if (success != true)
    print "Could not save the private token file." + "\n";
    exit
end

print "Example completed." + "\n";