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.
Chilkat Delphi DLL Downloads
var
success: Boolean;
stringCompare: HCkStringBuilder;
config: HCkJsonObject;
http: HCkHttp;
request: HCkHttpRequest;
response: HCkHttpResponse;
result: HCkJsonObject;
stringMatch1: Boolean;
tokenExpires: HCkDateTime;
stringMatch2: Boolean;
stringMatch3: Boolean;
validate6: HCkStringBuilder;
alphabet6: HCkStringBuilder;
charIndex6: Integer;
tokenLifetime: Integer;
tokenNow: HCkDateTime;
saved: HCkJsonObject;
begin
success := False;
stringCompare := CkStringBuilder_Create();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this configuration private, outside public web content and source control.
config := CkJsonObject_Create();
CkJsonObject_putStrict(config,True);
success := CkJsonObject_LoadFile(config,'qa_data/azure/keyvault.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load private Key Vault configuration.');
Exit;
end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
CkHttp_putVerboseLogging(http,False);
request := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(request,'GET');
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
// Azure VM IMDS is a link-local HTTP endpoint. Do not proxy this request.
CkHttp_putUseIEProxy(http,False);
CkHttp_putProxyDomain(http,'');
CkHttp_putConnectTimeout(http,5);
CkHttpRequest_putHttpVerb(request,'GET');
CkHttpRequest_AddHeader(request,'Metadata','true');
CkHttpRequest_AddParam(request,'api-version','2018-02-01');
CkHttpRequest_AddParam(request,'resource','https://vault.azure.net');
if (CkJsonObject_HasMember(config,'managed_identity_client_id') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'managed_identity_client_id'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'managed_identity_client_id') <> 1) or (stringMatch1 = True)) then
begin
Memo1.Lines.Add('Missing or invalid managed_identity_client_id.');
Exit;
end;
CkHttpRequest_AddParam(request,'client_id',CkJsonObject__stringOf(config,'managed_identity_client_id'));
end;
tokenExpires := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(tokenExpires);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read time.');
Exit;
end;
success := CkHttp_HttpReq(http,'http://169.254.169.254/metadata/identity/oauth2/token',request,response);
if (success <> True) then
begin
Memo1.Lines.Add('IMDS request failed; run on an Azure VM with managed identity enabled.');
Exit;
end;
if (CkHttpResponse_getStatusCode(response) <> 200) then
begin
Memo1.Lines.Add('Unexpected HTTP status; inspect request ID and diagnostics privately. Reconcile writes before retrying.');
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
begin
Memo1.Lines.Add('Invalid JSON response.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'access_token'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'access_token') <> 1) or (stringMatch2 = True)) then
begin
Memo1.Lines.Add('Missing or invalid access_token.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'token_type'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'Bearer',True);
if (stringMatch3 <> True) then
begin
Memo1.Lines.Add('Expected Bearer token.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(result,'expires_in') <> 2) and (CkJsonObject_JsonTypeOf(result,'expires_in') <> 1)) then
begin
Memo1.Lines.Add('Missing token lifetime.');
Exit;
end;
validate6 := CkStringBuilder_Create();
alphabet6 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate6,CkJsonObject__stringOf(result,'expires_in'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not validate token lifetime.');
Exit;
end;
success := CkStringBuilder_Append(alphabet6,'0123456789');
if (success <> True) then
begin
Memo1.Lines.Add('Could not initialize validation.');
Exit;
end;
if ((CkStringBuilder_getLength(validate6) < 1) or (CkStringBuilder_getLength(validate6) > 8)) then
begin
Memo1.Lines.Add('Invalid token lifetime length.');
Exit;
end;
charIndex6 := 0;
while (charIndex6 < CkStringBuilder_getLength(validate6)) do
begin
if (CkStringBuilder_Contains(alphabet6,CkStringBuilder__getRange(validate6,charIndex6,1,False),True) <> True) then
begin
Memo1.Lines.Add('Invalid character in token lifetime.');
Exit;
end;
charIndex6 := charIndex6 + 1;
end;
tokenLifetime := CkJsonObject_IntOf(result,'expires_in');
if ((tokenLifetime <= 60) or (tokenLifetime > 604800)) then
begin
Memo1.Lines.Add('Unexpected token lifetime.');
Exit;
end;
success := CkDateTime_AddSeconds(tokenExpires,tokenLifetime);
if (success <> True) then
begin
Memo1.Lines.Add('Could not calculate expiration.');
Exit;
end;
tokenNow := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(tokenNow);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read time.');
Exit;
end;
if (CkDateTime_DiffSeconds(tokenExpires,tokenNow) <= 60) then
begin
Memo1.Lines.Add('Token expired before it could be saved.');
Exit;
end;
saved := CkJsonObject_Create();
success := CkJsonObject_UpdateString(saved,'access_token',CkJsonObject__stringOf(result,'access_token'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set access_token.');
Exit;
end;
success := CkJsonObject_UpdateString(saved,'expires_at',CkDateTime__getAsTimestamp(tokenExpires,False));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set expires_at.');
Exit;
end;
success := CkJsonObject_WriteFile(saved,'qa_data/tokens/azureKeyVaultToken.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not save the private token file.');
Exit;
end;
Memo1.Lines.Add('Example completed.');
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(config);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(request);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkDateTime_Dispose(tokenExpires);
CkStringBuilder_Dispose(validate6);
CkStringBuilder_Dispose(alphabet6);
CkDateTime_Dispose(tokenNow);
CkJsonObject_Dispose(saved);