Azure Key Vault: Exchange a Workload Identity Token
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.
Configure an Entra federated identity credential with the exact external issuer, subject, and audience (commonly api://AzureADTokenExchange). Provide client_id and tenant_id. Have the trusted workload runtime supply a fresh projected JWT at qa_data/azure/federated-token.jwt before each exchange; adapt this path to your runtime-provided token path. The application forwards this assertion to the fixed tenant endpoint; Entra validates the federation trust. This does not mint or locally trust an arbitrary external token.
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"tenant_id"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"tenant_id") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid tenant_id.\n");
return;
}
CkStringBuilderW validate5;
CkStringBuilderW alphabet5;
success = validate5.Append(config.stringOf(L"tenant_id"));
if (success != true) {
wprintf(L"Could not validate tenant GUID.\n");
return;
}
success = alphabet5.Append(L"0123456789abcdefABCDEF-");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate5.get_Length() < 36) || (validate5.get_Length() > 36)) {
wprintf(L"Invalid tenant GUID 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 tenant GUID.\n");
return;
}
charIndex5 = charIndex5 + 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;
}
// Your trusted workload runtime must refresh this projected token file.
CkStringBuilderW projected;
success = projected.LoadFile(L"qa_data/azure/federated-token.jwt",L"utf-8");
if (success != true) {
wprintf(L"Could not read projected workload token.\n");
return;
}
success = projected.Trim();
if (success != true) {
wprintf(L"Could not trim token.\n");
return;
}
if (projected.get_Length() == 0) {
wprintf(L"Projected token is empty.\n");
return;
}
const wchar_t *assertion = projected.getAsString();
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"scope",L"https://vault.azure.net/.default");
request.AddParam(L"grant_type",L"client_credentials");
request.AddParam(L"client_assertion_type",L"urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
request.AddParam(L"client_assertion",assertion);
CkDateTimeW tokenExpires;
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read time.\n");
return;
}
success = http.HttpReq(tokenUrl.getAsString(),request,response);
if (success != true) {
wprintf(L"Token exchange failed; inspect diagnostics privately.\n");
return;
}
if (response.get_StatusCode() != 200) {
wprintf(L"Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.\n");
return;
}
success = result.Load(response.bodyStr());
if (success != true) {
wprintf(L"Invalid JSON response.\n");
return;
}
stringCompare.SetString(result.stringOf(L"access_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"access_token") != 1) || (stringMatch3 == true)) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
stringCompare.SetString(result.stringOf(L"token_type"));
bool stringMatch4 = stringCompare.ContentsEqual(L"Bearer",true);
if (stringMatch4 != true) {
wprintf(L"Expected Bearer token.\n");
return;
}
if ((result.JsonTypeOf(L"expires_in") != 2)) {
wprintf(L"Missing token lifetime.\n");
return;
}
CkStringBuilderW validate8;
CkStringBuilderW alphabet8;
success = validate8.Append(result.stringOf(L"expires_in"));
if (success != true) {
wprintf(L"Could not validate token lifetime.\n");
return;
}
success = alphabet8.Append(L"0123456789");
if (success != true) {
wprintf(L"Could not initialize validation.\n");
return;
}
if ((validate8.get_Length() < 1) || (validate8.get_Length() > 8)) {
wprintf(L"Invalid token lifetime length.\n");
return;
}
int charIndex8 = 0;
while ((charIndex8 < validate8.get_Length())) {
if (alphabet8.Contains(validate8.getRange(charIndex8,1,false),true) != true) {
wprintf(L"Invalid character in token lifetime.\n");
return;
}
charIndex8 = charIndex8 + 1;
}
int tokenLifetime = result.IntOf(L"expires_in");
if ((tokenLifetime <= 60) || (tokenLifetime > 604800)) {
wprintf(L"Unexpected token lifetime.\n");
return;
}
success = tokenExpires.AddSeconds(tokenLifetime);
if (success != true) {
wprintf(L"Could not calculate expiration.\n");
return;
}
CkDateTimeW tokenNow;
success = tokenNow.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read time.\n");
return;
}
if (tokenExpires.DiffSeconds(tokenNow) <= 60) {
wprintf(L"Token expired before it could be saved.\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",tokenExpires.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 the private token file.\n");
return;
}
wprintf(L"Example completed.\n");
}