Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

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.

Microsoft API reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkUrlW.h>
#include <CkJsonArrayW.h>

void ChilkatSample(void)
    {
    bool 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.
    CkJsonObjectW token;
    token.put_Strict(true);
    success = token.LoadFile(L"qa_data/tokens/azureToken.json");
    if (success != true) {
        wprintf(L"Could not load the private Azure Resource Manager token file.\n");
        return;
    }

    if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"A nonempty access_token string is required.\n");
        return;
    }

    //  Use your subscription ID as a string. The all-zero value is only a placeholder.
    const wchar_t *subscriptionId = L"00000000-0000-0000-0000-000000000000";
    CkHttpW http;
    http.put_AuthToken(token.stringOf(L"access_token"));
    http.put_Accept(L"application/json");
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(30);
    http.put_ReadTimeout(60);
    success = http.SetUrlVar(L"subscriptionId",subscriptionId);
    if (success != true) {
        wprintf(L"Could not encode subscription ID.\n");
        return;
    }

    CkHttpResponseW response;
    CkJsonObjectW result;
    result.put_Strict(true);
    CkUrlW parsed;
    const wchar_t *resourceGroupName = L"my-resource-group";
    success = http.SetUrlVar(L"resourceGroupName",resourceGroupName);
    if (success != true) {
        wprintf(L"Could not encode resource group.\n");
        return;
    }

    const wchar_t *accountName = L"youruniquestorageaccount";
    success = http.SetUrlVar(L"accountName",accountName);
    if (success != true) {
        wprintf(L"Could not encode account name.\n");
        return;
    }

    const wchar_t *keysUrl = L"https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/listKeys?api-version=2026-09-01";

    success = http.HttpNoBody(L"POST",keysUrl,response);
    if (response.get_StatusCode() == 0) {
        wprintf(L"No HTTP response. Inspect LastErrorText privately; it may contain credentials.\n");
        return;
    }

    if ((response.get_StatusCode() != 200)) {
        wprintf(L"HTTP status: %d\n",response.get_StatusCode());
        wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
        wprintf(L"Retry-After: %s\n",response.getHeaderField(L"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.
        return;
    }

    if (success != true) {
        wprintf(L"The HTTP response could not be read completely.\n");
        return;
    }

    success = result.Load(response.bodyStr());
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    if (result.JsonTypeOf(L"keys") != 4) {
        wprintf(L"Missing or invalid keys.\n");
        return;
    }

    //  Move all clients and key-signed SAS dependencies away from key1 BEFORE rotating it.
    //  This example retrieves key1, then optionally regenerates key1 only.
    const wchar_t *keyName = L"key1";
    bool rotateKey = false;
    if (rotateKey == true) {
        CkJsonObjectW request;
        request.UpdateString(L"keyName",keyName);
        success = http.HttpJson(L"POST",L"https://management.azure.com/subscriptions/{$subscriptionId}/resourceGroups/{$resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{$accountName}/regenerateKey?api-version=2026-09-01",request,L"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 (response.get_StatusCode() == 0) {
            wprintf(L"No HTTP response. Inspect LastErrorText privately; it may contain credentials.\n");
            return;
        }

        if ((response.get_StatusCode() != 200)) {
            wprintf(L"HTTP status: %d\n",response.get_StatusCode());
            wprintf(L"Request ID: %s\n",response.getHeaderField(L"x-ms-request-id"));
            wprintf(L"Retry-After: %s\n",response.getHeaderField(L"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.
            return;
        }

        if (success != true) {
            wprintf(L"The HTTP response could not be read completely.\n");
            return;
        }

        success = result.Load(response.bodyStr());
        if (success != true) {
            wprintf(L"Expected a well-formed JSON response.\n");
            return;
        }

        if (result.JsonTypeOf(L"keys") != 4) {
            wprintf(L"Missing or invalid keys.\n");
            return;
        }

    }

    CkJsonArrayW keys;
    success = result.ArrayOf2(L"keys",keys);
    if (success != true) {
        wprintf(L"Could not read returned keys.\n");
        return;
    }

    CkJsonObjectW key;
    CkJsonObjectW privateKey;
    bool found = false;
    int i = 0;
    while ((i < keys.get_Size())) {
        success = keys.ObjectAt2(i,key);
        if (success != true) {
            wprintf(L"Invalid key entry.\n");
            return;
        }

        if (key.StringOfEquals(L"keyName",keyName,true) == true) {
            if ((key.JsonTypeOf(L"value") != 1) || (key.StringOfEquals(L"value",L"",true) == true)) {
                wprintf(L"Selected key has no value. Inspect permissions privately.\n");
                return;
            }

            privateKey.UpdateString(L"account_name",accountName);
            privateKey.UpdateString(L"key_name",keyName);
            privateKey.UpdateString(L"access_key",key.stringOf(L"value"));
            found = true;
        }

        i = i + 1;
    }

    if (found != true) {
        wprintf(L"Selected key was not returned.\n");
        return;
    }

    //  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 = privateKey.WriteFile(L"qa_data/azure/storage-key.json");
    if (success != true) {
        wprintf(L"Could not save key privately. If rotated, use List Keys to recover; do not regenerate again.\n");
        return;
    }

    wprintf(L"Selected key saved privately. Key name: %s\n",keyName);
    wprintf(L"Key regeneration requested: %d\n",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.
    }