Azure Key Vault: Get an OAuth2 Token with Client Credentials
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.
Uses the Microsoft Entra v2 tenant-specific token endpoint and https://vault.azure.net/.default scope. Set nonempty client_id, client_secret, and directory GUID tenant_id in the private configuration. Use the client secret VALUE, not its identifier. This is for confidential applications, never browser/mobile clients. Client credentials have no refresh token: request another access token when needed. The token file is plaintext and must be protected by OS permissions. Token issuance does not grant vault access; grant only the required data-plane permissions to the service principal through Azure RBAC or the vault's configured access-policy model. Contributor alone does not grant data-plane access. Prefer managed identity or workload federation where available.
Chilkat Delphi DLL Downloads
var
success: Boolean;
stringCompare: HCkStringBuilder;
config: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
stringMatch3: Boolean;
validate4: HCkStringBuilder;
alphabet4: HCkStringBuilder;
charIndex4: Integer;
http: HCkHttp;
request: HCkHttpRequest;
response: HCkHttpResponse;
result: HCkJsonObject;
tokenUrl: HCkStringBuilder;
expires: HCkDateTime;
stringMatch4: Boolean;
stringMatch5: Boolean;
lifetime: PWideChar;
validate5: HCkStringBuilder;
alphabet5: HCkStringBuilder;
charIndex5: Integer;
seconds: Integer;
now: 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;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'client_id'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'client_id') <> 1) or (stringMatch1 = True)) then
begin
Memo1.Lines.Add('Missing or invalid client_id.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'client_secret'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'client_secret') <> 1) or (stringMatch2 = True)) then
begin
Memo1.Lines.Add('Missing or invalid client_secret.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(config,'tenant_id'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(config,'tenant_id') <> 1) or (stringMatch3 = True)) then
begin
Memo1.Lines.Add('Missing or invalid tenant_id.');
Exit;
end;
validate4 := CkStringBuilder_Create();
alphabet4 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate4,CkJsonObject__stringOf(config,'tenant_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not validate tenant GUID.');
Exit;
end;
success := CkStringBuilder_Append(alphabet4,'0123456789abcdefABCDEF-');
if (success <> True) then
begin
Memo1.Lines.Add('Could not initialize validation.');
Exit;
end;
if ((CkStringBuilder_getLength(validate4) < 36) or (CkStringBuilder_getLength(validate4) > 36)) then
begin
Memo1.Lines.Add('Invalid tenant GUID length.');
Exit;
end;
charIndex4 := 0;
while (charIndex4 < CkStringBuilder_getLength(validate4)) do
begin
if (CkStringBuilder_Contains(alphabet4,CkStringBuilder__getRange(validate4,charIndex4,1,False),True) <> True) then
begin
Memo1.Lines.Add('Invalid character in tenant GUID.');
Exit;
end;
charIndex4 := charIndex4 + 1;
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);
tokenUrl := CkStringBuilder_Create();
success := CkStringBuilder_Append(tokenUrl,'https://login.microsoftonline.com/');
if (success <> True) then
begin
Memo1.Lines.Add('Could not construct URL or identifier.');
Exit;
end;
success := CkStringBuilder_Append(tokenUrl,CkJsonObject__stringOf(config,'tenant_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not construct URL or identifier.');
Exit;
end;
success := CkStringBuilder_Append(tokenUrl,'/oauth2/v2.0/token');
if (success <> True) then
begin
Memo1.Lines.Add('Could not construct URL or identifier.');
Exit;
end;
CkHttpRequest_putHttpVerb(request,'POST');
CkHttpRequest_putContentType(request,'application/x-www-form-urlencoded');
CkHttpRequest_AddParam(request,'client_id',CkJsonObject__stringOf(config,'client_id'));
CkHttpRequest_AddParam(request,'client_secret',CkJsonObject__stringOf(config,'client_secret'));
CkHttpRequest_AddParam(request,'scope','https://vault.azure.net/.default');
CkHttpRequest_AddParam(request,'grant_type','client_credentials');
// Use request-start time so network latency cannot extend the cached lifetime.
expires := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(expires);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read current time.');
Exit;
end;
success := CkHttp_HttpReq(http,CkStringBuilder__getAsString(tokenUrl),request,response);
if (success <> True) then
begin
Memo1.Lines.Add('Token request failed; inspect diagnostics privately.');
Exit;
end;
if (CkHttpResponse_getStatusCode(response) <> 200) then
begin
Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(response)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(response,'x-ms-request-id'));
// Do not print full response bodies, tokens, or diagnostic logs.
Memo1.Lines.Add('Request failed. Inspect private diagnostics; reconcile writes before retrying.');
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(response));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'access_token'));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(result,'access_token') <> 1) or (stringMatch4 = True)) then
begin
Memo1.Lines.Add('Missing or invalid access_token.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(result,'token_type'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'Bearer',True);
if (stringMatch5 <> True) then
begin
Memo1.Lines.Add('Expected a Bearer token.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'expires_in') <> 2) then
begin
Memo1.Lines.Add('Missing numeric token lifetime.');
Exit;
end;
lifetime := CkJsonObject__stringOf(result,'expires_in');
validate5 := CkStringBuilder_Create();
alphabet5 := CkStringBuilder_Create();
success := CkStringBuilder_Append(validate5,lifetime);
if (success <> True) then
begin
Memo1.Lines.Add('Could not validate expires_in.');
Exit;
end;
success := CkStringBuilder_Append(alphabet5,'0123456789');
if (success <> True) then
begin
Memo1.Lines.Add('Could not initialize validation.');
Exit;
end;
if ((CkStringBuilder_getLength(validate5) < 1) or (CkStringBuilder_getLength(validate5) > 8)) then
begin
Memo1.Lines.Add('Invalid expires_in length.');
Exit;
end;
charIndex5 := 0;
while (charIndex5 < CkStringBuilder_getLength(validate5)) do
begin
if (CkStringBuilder_Contains(alphabet5,CkStringBuilder__getRange(validate5,charIndex5,1,False),True) <> True) then
begin
Memo1.Lines.Add('Invalid character in expires_in.');
Exit;
end;
charIndex5 := charIndex5 + 1;
end;
seconds := CkJsonObject_IntOf(result,'expires_in');
if ((seconds <= 60) or (seconds > 604800)) then
begin
Memo1.Lines.Add('Unexpected token lifetime.');
Exit;
end;
success := CkDateTime_AddSeconds(expires,seconds);
if (success <> True) then
begin
Memo1.Lines.Add('Could not compute expiration.');
Exit;
end;
now := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read current time.');
Exit;
end;
if (CkDateTime_DiffSeconds(expires,now) <= 60) then
begin
Memo1.Lines.Add('Token is expired or near expiration. Obtain a new token before continuing.');
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(expires,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 token to the private token file.');
Exit;
end;
Memo1.Lines.Add('Access token saved privately. No refresh token is issued for client credentials.');
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(config);
CkStringBuilder_Dispose(validate4);
CkStringBuilder_Dispose(alphabet4);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(request);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkStringBuilder_Dispose(tokenUrl);
CkDateTime_Dispose(expires);
CkStringBuilder_Dispose(validate5);
CkStringBuilder_Dispose(alphabet5);
CkDateTime_Dispose(now);
CkJsonObject_Dispose(saved);