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

Azure Key Vault: Get an OAuth2 Token with Client Credentials

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.

Uses the Microsoft Entra v2 tenant-specific token endpoint and https://vault.azure.net/.default scope. Set nonempty client_id, client_secret, and directory GUID tenant_id in the private configuration. Use the client secret VALUE, not its identifier. This is for confidential applications, never browser/mobile clients. Client credentials have no refresh token: request another access token when needed. The token file is plaintext and must be protected by OS permissions. Token issuance does not grant vault access; grant only the required data-plane permissions to the service principal through Azure RBAC or the vault's configured access-policy model. Contributor alone does not grant data-plane access. Prefer managed identity or workload federation where available.

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

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

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

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

validate4 = Chilkat::CkStringBuilder.new()
alphabet4 = Chilkat::CkStringBuilder.new()
success = validate4.Append(config.stringOf("tenant_id"))
if (success != true)
    print "Could not validate tenant GUID." + "\n";
    exit
end

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

if ((validate4.get_Length() < 36) or (validate4.get_Length() > 36))
    print "Invalid tenant GUID length." + "\n";
    exit
end

charIndex4 = 0
while (charIndex4 < validate4.get_Length())
    if (alphabet4.Contains(validate4.getRange(charIndex4,1,false),true) != true)
        print "Invalid character in tenant GUID." + "\n";
        exit
    end

    charIndex4 = charIndex4 + 1
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)
tokenUrl = Chilkat::CkStringBuilder.new()
success = tokenUrl.Append("https://login.microsoftonline.com/")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = tokenUrl.Append(config.stringOf("tenant_id"))
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

success = tokenUrl.Append("/oauth2/v2.0/token")
if (success != true)
    print "Could not construct URL or identifier." + "\n";
    exit
end

request.put_HttpVerb("POST")
request.put_ContentType("application/x-www-form-urlencoded")
request.AddParam("client_id",config.stringOf("client_id"))
request.AddParam("client_secret",config.stringOf("client_secret"))
request.AddParam("scope","https://vault.azure.net/.default")
request.AddParam("grant_type","client_credentials")
#  Use request-start time so network latency cannot extend the cached lifetime.
expires = Chilkat::CkDateTime.new()
success = expires.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read current time." + "\n";
    exit
end

success = http.HttpReq(tokenUrl.getAsString(),request,response)
if (success != true)
    print "Token request failed; inspect diagnostics privately." + "\n";
    exit
end

if (response.get_StatusCode() != 200)
    print "HTTP status: " + response.get_StatusCode().to_s() + "\n";
    print "Request ID: " + response.getHeaderField("x-ms-request-id") + "\n";
    #  Do not print full response bodies, tokens, or diagnostic logs.
    print "Request failed. Inspect private diagnostics; reconcile writes before retrying." + "\n";
    exit
end

success = result.Load(response.bodyStr())
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

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

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

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

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

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

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

charIndex5 = 0
while (charIndex5 < validate5.get_Length())
    if (alphabet5.Contains(validate5.getRange(charIndex5,1,false),true) != true)
        print "Invalid character in expires_in." + "\n";
        exit
    end

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

success = expires.AddSeconds(seconds)
if (success != true)
    print "Could not compute expiration." + "\n";
    exit
end

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

if (expires.DiffSeconds(now) <= 60)
    print "Token is expired or near expiration. Obtain a new token before continuing." + "\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",expires.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 token to the private token file." + "\n";
    exit
end

print "Access token saved privately. No refresh token is issued for client credentials." + "\n";