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.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkDateTimeW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
CkJsonObjectW config;
config.put_Strict(true);
success = config.LoadFile(L"qa_data/azure/keyvault.json");
if (success != true) {
wprintf(L"Could not load private Key Vault configuration.\n");
return;
}
stringCompare.SetString(config.stringOf(L"client_id"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"client_id") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
stringCompare.SetString(config.stringOf(L"client_secret"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"client_secret") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid client_secret.\n");
return;
}
stringCompare.SetString(config.stringOf(L"tenant_id"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"tenant_id") != 1) || (stringMatch3 == true)) {
wprintf(L"Missing or invalid tenant_id.\n");
return;
}
CkStringBuilderW validate4;
CkStringBuilderW alphabet4;
success = validate4.Append(config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not validate tenant GUID.\n");
return;
}
success = alphabet4.Append(L"0123456789abcdefABCDEF-");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate4.get_Length() < 36) || (validate4.get_Length() > 36)) {
wprintf(L"Invalid tenant GUID length.\n");
return;
}
int charIndex4 = 0;
while ((charIndex4 < validate4.get_Length())) {
if (alphabet4.Contains(validate4.getRange(charIndex4,1,false),true) != true) {
wprintf(L"Invalid character in tenant GUID.\n");
return;
}
charIndex4 = charIndex4 + 1;
}
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
http.put_VerboseLogging(false);
CkHttpRequestW request;
request.put_HttpVerb(L"GET");
CkHttpResponseW response;
CkJsonObjectW result;
result.put_Strict(true);
CkStringBuilderW tokenUrl;
success = tokenUrl.Append(L"https://login.microsoftonline.com/");
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
success = tokenUrl.Append(config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
success = tokenUrl.Append(L"/oauth2/v2.0/token");
if (success != true) {
wprintf(L"Could not construct URL or identifier.\n");
return;
}
request.put_HttpVerb(L"POST");
request.put_ContentType(L"application/x-www-form-urlencoded");
request.AddParam(L"client_id",config.stringOf(L"client_id"));
request.AddParam(L"client_secret",config.stringOf(L"client_secret"));
request.AddParam(L"scope",L"https://vault.azure.net/.default");
request.AddParam(L"grant_type",L"client_credentials");
// Use request-start time so network latency cannot extend the cached lifetime.
CkDateTimeW expires;
success = expires.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read current time.\n");
return;
}
success = http.HttpReq(tokenUrl.getAsString(),request,response);
if (success != true) {
wprintf(L"Token request failed; inspect diagnostics privately.\n");
return;
}
if (response.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",response.get_StatusCode());
wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
// Do not print full response bodies, tokens, or diagnostic logs.
wprintf(L"Request failed. Inspect private diagnostics; reconcile writes before retrying.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Expected a well-formed JSON response.\n");
return;
}
stringCompare.SetString(result.stringOf(L"access_token"));
bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"access_token") != 1) || (stringMatch4 == true)) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
stringCompare.SetString(result.stringOf(L"token_type"));
bool stringMatch5 = stringCompare.ContentsEqual(L"Bearer",true);
if (stringMatch5 != true) {
wprintf(L"Expected a Bearer token.\n");
return;
}
if (result.JsonTypeOf(L"expires_in") != 2) {
wprintf(L"Missing numeric token lifetime.\n");
return;
}
const wchar_t *lifetime = result.stringOf(L"expires_in");
CkStringBuilderW validate5;
CkStringBuilderW alphabet5;
success = validate5.Append(lifetime);
if (success != true) {
wprintf(L"Could not validate expires_in.\n");
return;
}
success = alphabet5.Append(L"0123456789");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate5.get_Length() < 1) || (validate5.get_Length() > 8)) {
wprintf(L"Invalid expires_in length.\n");
return;
}
int charIndex5 = 0;
while ((charIndex5 < validate5.get_Length())) {
if (alphabet5.Contains(validate5.getRange(charIndex5,1,false),true) != true) {
wprintf(L"Invalid character in expires_in.\n");
return;
}
charIndex5 = charIndex5 + 1;
}
int seconds = result.IntOf(L"expires_in");
if ((seconds <= 60) || (seconds > 604800)) {
wprintf(L"Unexpected token lifetime.\n");
return;
}
success = expires.AddSeconds(seconds);
if (success != true) {
wprintf(L"Could not compute expiration.\n");
return;
}
CkDateTimeW now;
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read current time.\n");
return;
}
if (expires.DiffSeconds(now) <= 60) {
wprintf(L"Token is expired or near expiration. Obtain a new token before continuing.\n");
return;
}
CkJsonObjectW saved;
success = saved.UpdateString(L"access_token",result.stringOf(L"access_token"));
if (success != true) {
wprintf(L"Could not set access_token.\n");
return;
}
success = saved.UpdateString(L"expires_at",expires.getAsTimestamp(false));
if (success != true) {
wprintf(L"Could not set expires_at.\n");
return;
}
success = saved.WriteFile(L"qa_data/tokens/azureKeyVaultToken.json");
if (success != true) {
wprintf(L"Could not save token to the private token file.\n");
return;
}
wprintf(L"Access token saved privately. No refresh token is issued for client credentials.\n");
}