Azure Storage Accounts: Retrieve and Optionally Rotate a Storage Account Key
See more Azure Storage Accounts Examples
Uses List Keys to retrieve an account key, or regenerates only key1 when rotateKey=true. Saves only the selected secret to a private file and never prints it. The caller needs List Keys permission and, for rotation, Regenerate Key permission.
Regeneration immediately invalidates the old key and SAS signatures derived from it. First migrate all dependent clients to the other key; regenerate the unused key, distribute its new value securely, and only later consider rotating the other key. Do not regenerate both together. A failed local save does not undo rotation; recover using List Keys. Prefer Entra authentication where supported. See account key management.
These calls manage Azure resources at management.azure.com. They do not upload or download stored data. Supply a current Microsoft Entra access token for Azure Resource Manager in private qa_data/tokens/azureToken.json, with a nonempty access_token string. For v2 client credentials, request https://management.azure.com/.default; obtain a new token when it expires. A storage account key, SAS, Microsoft Graph token, or Storage data-plane token is not an ARM token. Never print the token or commit its file.
Azure RBAC must grant the caller the required management actions at the appropriate scope. An app registration alone does not grant resource access. Management permissions and blob/file data permissions are distinct. These examples target public Azure; sovereign clouds require the corresponding authority, ARM endpoint, token audience, and continuation-host validation.
Chilkat Delphi DLL Downloads
var
success: Boolean;
token: HCkJsonObject;
subscriptionId: PWideChar;
http: HCkHttp;
response: HCkHttpResponse;
result: HCkJsonObject;
parsed: HCkUrl;
resourceGroupName: PWideChar;
accountName: PWideChar;
keysUrl: PWideChar;
keyName: PWideChar;
rotateKey: Boolean;
request: HCkJsonObject;
keys: HCkJsonArray;
key: HCkJsonObject;
privateKey: HCkJsonObject;
found: Boolean;
i: Integer;
begin
success := False;
// This example requires the Chilkat API to have been previously unlocked.
// See Global.UnlockBundle for sample code.
// This is Azure Resource Manager (the management plane), not a blob data request.
// Load an unexpired Microsoft Entra token whose audience is Azure Resource Manager.
// For the v2 token endpoint, request scope https://management.azure.com/.default.
// Keep the token file private and out of source control and public web directories.
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/azureToken.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the private Azure Resource Manager token file.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('A nonempty access_token string is required.');
Exit;
end;
// Use your subscription ID as a string. The all-zero value is only a placeholder.
subscriptionId := '00000000-0000-0000-0000-000000000000';
http := CkHttp_Create();
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
CkHttp_putAccept(http,'application/json');
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,30);
CkHttp_putReadTimeout(http,60);
success := CkHttp_SetUrlVar(http,'subscriptionId',subscriptionId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode subscription ID.');
Exit;
end;
response := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
parsed := CkUrl_Create();
resourceGroupName := 'my-resource-group';
success := CkHttp_SetUrlVar(http,'resourceGroupName',resourceGroupName);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode resource group.');
Exit;
end;
accountName := 'youruniquestorageaccount';
success := CkHttp_SetUrlVar(http,'accountName',accountName);
if (success <> True) then
begin
Memo1.Lines.Add('Could not encode account name.');
Exit;
end;
keysUrl := 'https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/listKeys?api-version=2026-09-01';
success := CkHttp_HttpNoBody(http,'POST',keysUrl,response);
if (CkHttpResponse_getStatusCode(response) = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect LastErrorText privately; it may contain credentials.');
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'));
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
// Inspect the error body privately. Do not log tokens, headers, or full responses.
// For 401 check the token/audience; for 403 check Azure RBAC and policy.
// Honor Retry-After for 429 and use bounded backoff for transient failures.
Exit;
end;
if (success <> True) then
begin
Memo1.Lines.Add('The HTTP response could not be read completely.');
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;
if (CkJsonObject_JsonTypeOf(result,'keys') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid keys.');
Exit;
end;
// Move all clients and key-signed SAS dependencies away from key1 BEFORE rotating it.
// This example retrieves key1, then optionally regenerates key1 only.
keyName := 'key1';
rotateKey := False;
if (rotateKey = True) then
begin
request := CkJsonObject_Create();
CkJsonObject_UpdateString(request,'keyName',keyName);
success := CkHttp_HttpJson(http,'POST','https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/regenerateKey?api-version=2026-09-01',request,'application/json',response);
// Do not retry regeneration after an uncertain transport result: list keys
// to recover the current value. Repeating regeneration invalidates it again.
if (CkHttpResponse_getStatusCode(response) = 0) then
begin
Memo1.Lines.Add('No HTTP response. Inspect LastErrorText privately; it may contain credentials.');
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'));
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(response,'Retry-After'));
// Inspect the error body privately. Do not log tokens, headers, or full responses.
// For 401 check the token/audience; for 403 check Azure RBAC and policy.
// Honor Retry-After for 429 and use bounded backoff for transient failures.
Exit;
end;
if (success <> True) then
begin
Memo1.Lines.Add('The HTTP response could not be read completely.');
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;
if (CkJsonObject_JsonTypeOf(result,'keys') <> 4) then
begin
Memo1.Lines.Add('Missing or invalid keys.');
Exit;
end;
end;
keys := CkJsonArray_Create();
success := CkJsonObject_ArrayOf2(result,'keys',keys);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read returned keys.');
Exit;
end;
key := CkJsonObject_Create();
privateKey := CkJsonObject_Create();
found := False;
i := 0;
while (i < CkJsonArray_getSize(keys)) do
begin
success := CkJsonArray_ObjectAt2(keys,i,key);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid key entry.');
Exit;
end;
if (CkJsonObject_StringOfEquals(key,'keyName',keyName,True) = True) then
begin
if ((CkJsonObject_JsonTypeOf(key,'value') <> 1) or (CkJsonObject_StringOfEquals(key,'value','',True) = True)) then
begin
Memo1.Lines.Add('Selected key has no value. Inspect permissions privately.');
Exit;
end;
CkJsonObject_UpdateString(privateKey,'account_name',accountName);
CkJsonObject_UpdateString(privateKey,'key_name',keyName);
CkJsonObject_UpdateString(privateKey,'access_key',CkJsonObject__stringOf(key,'value'));
found := True;
end;
i := i + 1;
end;
if (found <> True) then
begin
Memo1.Lines.Add('Selected key was not returned.');
Exit;
end;
// Pre-create this private directory with restrictive OS permissions. This file
// contains an account-wide secret; never commit it or put it in web content.
success := CkJsonObject_WriteFile(privateKey,'qa_data/azure/storage-key.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not save key privately. If rotated, use List Keys to recover; do not regenerate again.');
Exit;
end;
Memo1.Lines.Add('Selected key saved privately. Key name: ' + keyName);
Memo1.Lines.Add('Key regeneration requested: ' + IntToStr(Ord(rotateKey)));
// Distribute the current key through your application's secret-management process.
// Rotate the other key in a separate maintenance step after clients are migrated.
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(response);
CkJsonObject_Dispose(result);
CkUrl_Dispose(parsed);
CkJsonObject_Dispose(request);
CkJsonArray_Dispose(keys);
CkJsonObject_Dispose(key);
CkJsonObject_Dispose(privateKey);