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

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.

Microsoft reference

Chilkat C# Downloads

C#
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;
}

stringCompare.SetString(config.StringOf("client_id"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("client_id") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid client_id.");
    return;
}

stringCompare.SetString(config.StringOf("tenant_id"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((config.JsonTypeOf("tenant_id") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid tenant_id.");
    return;
}

Chilkat.StringBuilder validate5 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet5 = new Chilkat.StringBuilder();
success = validate5.Append(config.StringOf("tenant_id"));
if (success != true) {
    Debug.WriteLine("Could not validate tenant GUID.");
    return;
}

success = alphabet5.Append("0123456789abcdefABCDEF-");
if (success != true) {
    Debug.WriteLine("Could not initialize validation.");
    return;
}

if ((validate5.Length < 36) || (validate5.Length > 36)) {
    Debug.WriteLine("Invalid tenant GUID length.");
    return;
}

int charIndex5 = 0;
while ((charIndex5 < validate5.Length)) {
    if (alphabet5.Contains(validate5.GetRange(charIndex5,1,false),true) != true) {
        Debug.WriteLine("Invalid character in tenant GUID.");
        return;
    }

    charIndex5 = charIndex5 + 1;
}

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;
Chilkat.StringBuilder tokenUrl = new Chilkat.StringBuilder();
success = tokenUrl.Append("https://login.microsoftonline.com/");
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = tokenUrl.Append(config.StringOf("tenant_id"));
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

success = tokenUrl.Append("/oauth2/v2.0/token");
if (success != true) {
    Debug.WriteLine("Could not construct URL or identifier.");
    return;
}

//  Your trusted workload runtime must refresh this projected token file.
Chilkat.StringBuilder projected = new Chilkat.StringBuilder();
success = projected.LoadFile("qa_data/azure/federated-token.jwt","utf-8");
if (success != true) {
    Debug.WriteLine("Could not read projected workload token.");
    return;
}

success = projected.Trim();
if (success != true) {
    Debug.WriteLine("Could not trim token.");
    return;
}

if (projected.Length == 0) {
    Debug.WriteLine("Projected token is empty.");
    return;
}

string assertion = projected.GetAsString();
request.HttpVerb = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AddParam("client_id",config.StringOf("client_id"));
request.AddParam("scope","https://vault.azure.net/.default");
request.AddParam("grant_type","client_credentials");
request.AddParam("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
request.AddParam("client_assertion",assertion);
Chilkat.CkDateTime tokenExpires = new Chilkat.CkDateTime();
success = tokenExpires.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read time.");
    return;
}

success = http.HttpReq(tokenUrl.GetAsString(),request,response);
if (success != true) {
    Debug.WriteLine("Token exchange failed; inspect diagnostics privately.");
    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 stringMatch3 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("access_token") != 1) || (stringMatch3 == true)) {
    Debug.WriteLine("Missing or invalid access_token.");
    return;
}

stringCompare.SetString(result.StringOf("token_type"));
bool stringMatch4 = stringCompare.ContentsEqual("Bearer",true);
if (stringMatch4 != true) {
    Debug.WriteLine("Expected Bearer token.");
    return;
}

if ((result.JsonTypeOf("expires_in") != 2)) {
    Debug.WriteLine("Missing token lifetime.");
    return;
}

Chilkat.StringBuilder validate8 = new Chilkat.StringBuilder();
Chilkat.StringBuilder alphabet8 = new Chilkat.StringBuilder();
success = validate8.Append(result.StringOf("expires_in"));
if (success != true) {
    Debug.WriteLine("Could not validate token lifetime.");
    return;
}

success = alphabet8.Append("0123456789");
if (success != true) {
    Debug.WriteLine("Could not initialize validation.");
    return;
}

if ((validate8.Length < 1) || (validate8.Length > 8)) {
    Debug.WriteLine("Invalid token lifetime length.");
    return;
}

int charIndex8 = 0;
while ((charIndex8 < validate8.Length)) {
    if (alphabet8.Contains(validate8.GetRange(charIndex8,1,false),true) != true) {
        Debug.WriteLine("Invalid character in token lifetime.");
        return;
    }

    charIndex8 = charIndex8 + 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.");