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

CkPerl
use chilkat();

$success = 0;

$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(1);
$success = $config->LoadFile("qa_data/azure/keyvault.json");
if ($success != 1) {
    print "Could not load private Key Vault configuration." . "\r\n";
    exit;
}

$http = chilkat::CkHttp->new();
$http->put_RequireSslCertVerify(1);
$http->put_FollowRedirects(0);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(60);
$http->put_VerboseLogging(0);
$request = chilkat::CkHttpRequest->new();
$request->put_HttpVerb("GET");
$response = chilkat::CkHttpResponse->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
#  Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
$http->put_UseIEProxy(0);
$http->put_ProxyDomain("");
$http->put_ConnectTimeout(5);
$request->put_HttpVerb("GET");
$request->AddHeader("Metadata","true");
$request->AddParam("api-version","2018-02-01");
$request->AddParam("resource","https://vault.azure.net");
if ($config->HasMember("managed_identity_client_id") == 1) {
    $stringCompare->SetString($config->stringOf("managed_identity_client_id"));
    $stringMatch1 = $stringCompare->ContentsEqual("",1);
    if (($config->JsonTypeOf("managed_identity_client_id") != 1) or ($stringMatch1 == 1)) {
        print "Missing or invalid managed_identity_client_id." . "\r\n";
        exit;
    }

    $request->AddParam("client_id",$config->stringOf("managed_identity_client_id"));
}

$tokenExpires = chilkat::CkDateTime->new();
$success = $tokenExpires->SetFromCurrentSystemTime();
if ($success != 1) {
    print "Could not read time." . "\r\n";
    exit;
}

$success = $http->HttpReq("http://169.254.169.254/metadata/identity/oauth2/token",$request,$response);
if ($success != 1) {
    print "IMDS request failed; run on an Azure VM with managed identity enabled." . "\r\n";
    exit;
}

if ($response->get_StatusCode() != 200) {
    print "Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying." . "\r\n";
    exit;
}

$success = $result->Load($response->bodyStr());
if ($success != 1) {
    print "Invalid JSON response." . "\r\n";
    exit;
}

$stringCompare->SetString($result->stringOf("access_token"));
$stringMatch2 = $stringCompare->ContentsEqual("",1);
if (($result->JsonTypeOf("access_token") != 1) or ($stringMatch2 == 1)) {
    print "Missing or invalid access_token." . "\r\n";
    exit;
}

$stringCompare->SetString($result->stringOf("token_type"));
$stringMatch3 = $stringCompare->ContentsEqual("Bearer",1);
if ($stringMatch3 != 1) {
    print "Expected Bearer token." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("expires_in") != 2) and ($result->JsonTypeOf("expires_in") != 1)) {
    print "Missing token lifetime." . "\r\n";
    exit;
}

$validate6 = chilkat::CkStringBuilder->new();
$alphabet6 = chilkat::CkStringBuilder->new();
$success = $validate6->Append($result->stringOf("expires_in"));
if ($success != 1) {
    print "Could not validate token lifetime." . "\r\n";
    exit;
}

$success = $alphabet6->Append("0123456789");
if ($success != 1) {
    print "Could not initialize validation." . "\r\n";
    exit;
}

if (($validate6->get_Length() < 1) or ($validate6->get_Length() > 8)) {
    print "Invalid token lifetime length." . "\r\n";
    exit;
}

$charIndex6 = 0;
while (($charIndex6 < $validate6->get_Length())) {
    if ($alphabet6->Contains($validate6->getRange($charIndex6,1,0),1) != 1) {
        print "Invalid character in token lifetime." . "\r\n";
        exit;
    }

    $charIndex6 = $charIndex6 + 1;
}

$tokenLifetime = $result->IntOf("expires_in");
if (($tokenLifetime <= 60) or ($tokenLifetime > 604800)) {
    print "Unexpected token lifetime." . "\r\n";
    exit;
}

$success = $tokenExpires->AddSeconds($tokenLifetime);
if ($success != 1) {
    print "Could not calculate expiration." . "\r\n";
    exit;
}

$tokenNow = chilkat::CkDateTime->new();
$success = $tokenNow->SetFromCurrentSystemTime();
if ($success != 1) {
    print "Could not read time." . "\r\n";
    exit;
}

if ($tokenExpires->DiffSeconds($tokenNow) <= 60) {
    print "Token expired before it could be saved." . "\r\n";
    exit;
}

$saved = chilkat::CkJsonObject->new();
$success = $saved->UpdateString("access_token",$result->stringOf("access_token"));
if ($success != 1) {
    print "Could not set access_token." . "\r\n";
    exit;
}

$success = $saved->UpdateString("expires_at",$tokenExpires->getAsTimestamp(0));
if ($success != 1) {
    print "Could not set expires_at." . "\r\n";
    exit;
}

$success = $saved->WriteFile("qa_data/tokens/azureKeyVaultToken.json");
if ($success != 1) {
    print "Could not save the private token file." . "\r\n";
    exit;
}

print "Example completed." . "\r\n";