Sample code for 30+ languages & platforms
Unicode C++ 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 Unicode C++ Downloads

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

    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);
    //  Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
    http.put_UseIEProxy(false);
    http.put_ProxyDomain(L"");
    http.put_ConnectTimeout(5);
    request.put_HttpVerb(L"GET");
    request.AddHeader(L"Metadata",L"true");
    request.AddParam(L"api-version",L"2018-02-01");
    request.AddParam(L"resource",L"https://vault.azure.net");
    if (config.HasMember(L"managed_identity_client_id") == true) {
        stringCompare.SetString(config.stringOf(L"managed_identity_client_id"));
        bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
        if ((config.JsonTypeOf(L"managed_identity_client_id") != 1) || (stringMatch1 == true)) {
            wprintf(L"Missing or invalid managed_identity_client_id.\n");
            return;
        }

        request.AddParam(L"client_id",config.stringOf(L"managed_identity_client_id"));
    }

    CkDateTimeW tokenExpires;
    success = tokenExpires.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read time.\n");
        return;
    }

    success = http.HttpReq(L"http://169.254.169.254/metadata/identity/oauth2/token",request,response);
    if (success != true) {
        wprintf(L"IMDS request failed; run on an Azure VM with managed identity enabled.\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 stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"access_token") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid access_token.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"token_type"));
    bool stringMatch3 = stringCompare.ContentsEqual(L"Bearer",true);
    if (stringMatch3 != true) {
        wprintf(L"Expected Bearer token.\n");
        return;
    }

    if ((result.JsonTypeOf(L"expires_in") != 2) && (result.JsonTypeOf(L"expires_in") != 1)) {
        wprintf(L"Missing token lifetime.\n");
        return;
    }

    CkStringBuilderW validate6;
    CkStringBuilderW alphabet6;
    success = validate6.Append(result.stringOf(L"expires_in"));
    if (success != true) {
        wprintf(L"Could not validate token lifetime.\n");
        return;
    }

    success = alphabet6.Append(L"0123456789");
    if (success != true) {
        wprintf(L"Could not initialize validation.\n");
        return;
    }

    if ((validate6.get_Length() < 1) || (validate6.get_Length() > 8)) {
        wprintf(L"Invalid token lifetime length.\n");
        return;
    }

    int charIndex6 = 0;
    while ((charIndex6 < validate6.get_Length())) {
        if (alphabet6.Contains(validate6.getRange(charIndex6,1,false),true) != true) {
            wprintf(L"Invalid character in token lifetime.\n");
            return;
        }

        charIndex6 = charIndex6 + 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");
    }