共用方式為


適用於 C++ 的 Azure 身分識別用戶端連結庫中的認證鏈結

Azure 身分識別客戶端連結庫提供 認證—衍生自 Azure Core 連結庫 TokenCredential 抽象基類的公用類型。 憑證代表從 Microsoft Entra ID 取得存取權杖的特定驗證流程。 這些憑證可以串聯在一起,以形成一個按順序嘗試的認證機制序列。

鏈結認證的運作方式

在執行階段,認證鏈會嘗試使用序列的第一個憑證進行驗證。 如果該認證無法取得存取權杖,則會嘗試序列中的下一個認證,以此類推,直到成功取得存取權杖為止。 下列順序圖說明此行為:

顯示認證鏈結順序的圖表。

為什麼要使用認證鏈結?

鏈結認證可以提供下列優點:

  • 環境感知:根據應用程式執行所在的環境,自動選取最適當的認證。 如果沒有它,您必須撰寫如下的程式代碼:

    // Set up credential based on environment (Azure or local development)
    std::shared_ptr<Azure::Core::Credentials::TokenCredential> credential;
    if (std::getenv("WEBSITE_HOSTNAME"))
    {
        credential = std::make_shared<Azure::Identity::ManagedIdentityCredential>();
    }
    else
    {
        credential = std::make_shared<Azure::Identity::AzureCliCredential>();
    }
    
  • 順暢轉換:您的應用程式可以在不變更驗證碼的情況下,從本機開發移至預備或生產環境。

  • 提升彈性:包含一個後援機制,在前一個憑證無法取得存取權杖時會移至下一個憑證。

如何選擇鏈結認證

使用C++時,認證鏈結有兩個選項:

  • 使用預先設定的鏈結:使用由 DefaultAzureCredential 類型實作的預先設定鏈結。 針對這個方法,請參閱 DefaultAzureCredential 概觀一節。
  • 建置自定義憑證鏈:從空白鏈結開始,並僅包含您所需的內容。 針對這個方法,請參閱 ChainedTokenCredential 概觀一節。

DefaultAzureCredential 概觀

DefaultAzureCredential 是具有偏向性且預先設定的認證鏈。 其設計支援許多環境,以及最常見的驗證流程和開發人員工具。 在圖形化形式中,基礎鏈結看起來像這樣:

顯示 DefaultAzureCredential 驗證流程的圖表。

DefaultAzureCredential 嘗試認證的順序如下。

訂單 憑據 說明
1 環境 讀取環境變數集合,以判斷應用程式服務主體(應用程式使用者)是否已為應用程式設定。 如是,DefaultAzureCredential 則會使用這些值向 Azure 驗證應用程式。 此方法最常用於伺服器環境,但也可以在本機開發時使用。
2 工作負載身分識別 如果應用程式部署至已啟用工作負載識別的 Azure 主機,請驗證該帳戶。
3 受控識別 如果應用程式部署至已啟用受控識別的 Azure 主機,請使用該受控識別向 Azure 驗證應用程式。
4 Azure CLI 如果開發人員使用 Azure CLI 的 az login 命令向 Azure 進行驗證,請使用相同的帳戶向 Azure 驗證應用程式。

在最簡單的形式中,您可以使用 DefaultAzureCredential 的無參數版本,如下所示:

#include <azure/identity/default_azure_credential.hpp>
#include <azure/storage/blobs/blob_client.hpp>

int main()
{
    // create a credential
    auto credential = std::make_shared<Azure::Identity::DefaultAzureCredential>();

    // create a Blob service client
    auto blobUrl = "https://<my_account_name>.blob.core.windows.net/mycontainer/myblob";
    Azure::Storage::Blobs::BlobClient blobClient{blobUrl, credential};
}

如何自訂 DefaultAzureCredential

下列各節說明控制鏈結中包含哪些認證的策略。

排除認證類型類別

若要排除所有 Developer toolDeployed service 認證,請將環境變數 AZURE_TOKEN_CREDENTIALS 分別設定為 proddev。 使用prod值時,基礎憑證鏈如下所示:

顯示 DefaultAzureCredential 且AZURE_TOKEN_CREDENTIALS設定為 『prod』 的圖表。

使用的值 dev 時,鏈結只會包含 AzureCliCredential

若要確保環境變數已定義並設定為支援的字串,請傳遞 trueDefaultAzureCredential 建構函式:

auto credential = std::make_shared<Azure::Identity::DefaultAzureCredential>(true);

這很重要

1.13.1 版及更新版本的套件支援 azure-identity-cpp 上述建構函式多載。

使用特定認證

若要排除除了一個認證以外的所有認證,請將環境變數 AZURE_TOKEN_CREDENTIALS 設定為認證名稱。 例如,您可以將 設定為 ,以減少的DefaultAzureCredential鏈結AzureCliCredentialAZURE_TOKEN_CREDENTIALSAzureCliCredential 字串比較是以不區分大小寫的方式執行。 環境變數的有效字串值包括:

  • AzureCliCredential
  • EnvironmentCredential
  • ManagedIdentityCredential
  • WorkloadIdentityCredential

若要確保環境變數已定義並設定為支援的字串,請傳遞 trueDefaultAzureCredential 建構函式:

auto credential = std::make_shared<Azure::Identity::DefaultAzureCredential>(true);

這很重要

1.13.1 版及更新版本的套件支援 azure-identity-cpp 上述建構函式多載。

ChainedTokenCredential 概觀

ChainedTokenCredential 是一個空鏈結,可供您新增認證以符合應用程式需求。 例如:

#include <azure/identity/azure_cli_credential.hpp>
#include <azure/identity/chained_token_credential.hpp>
#include <azure/identity/managed_identity_credential.hpp>
#include <azure/storage/blobs/blob_client.hpp>

int main()
{
    // create a credential
    auto credential = std::make_shared<Azure::Identity::ChainedTokenCredential>(
        Azure::Identity::ChainedTokenCredential::Sources{
            std::make_shared<Azure::Identity::ManagedIdentityCredential>(),
            std::make_shared<Azure::Identity::AzureCliCredential>()});

    // create a Blob service client
    auto blobUrl = "https://<my_account_name>.blob.core.windows.net/mycontainer/myblob";
    Azure::Storage::Blobs::BlobClient blobClient{blobUrl, credential};
}

上述程式代碼範例會建立由兩個認證組成的量身訂做認證鏈結。 先嘗試 ManagedIdentityCredential,然後視需要 AzureCliCredential。 在圖形化形式中,鏈條看起來像這樣:

此圖顯示由 ManagedIdentityCredential 和 AzureCliCredential 所組成的 ChainedTokenCredential 實例驗證流程。

小提示

為了提升效能,請優化 ChainedTokenCredential 中的認證排序,按照從最常使用到最少使用的順序排列。

DefaultAzureCredential 的使用指引

DefaultAzureCredential 無疑是開始使用 Azure 身分識別用戶端程式庫的最簡單方式,但這種便利性也意味著需要作出一些取捨。 將應用程式部署至 Azure 之後,您應該瞭解應用程式的驗證需求。 因此,請將 DefaultAzureCredential 取代為特定的 TokenCredential 實作,例如 ManagedIdentityCredential

原因如下:

  • 偵錯挑戰:當驗證失敗時,偵錯和識別違規認證可能會很困難。 您必須啟用記錄,才能查看從一個認證到下一個認證的進展,以及每個認證的成功/失敗狀態。 如需詳細資訊,請參閱偵錯鏈結認證
  • 效能負擔問題:循序嘗試多個認證可能會導致效能負擔的問題。 例如,在本地開發環境中運行時,受控識別無法使用。 因此,ManagedIdentityCredential 總是在本機開發環境中失敗。
  • 無法預測的行為DefaultAzureCredential 會檢查特定環境變數是否存在。 有人可能會在主機電腦上的系統層級新增或修改這些環境變數。 這些變更會全域套用,並因此改變 DefaultAzureCredential 在該電腦上執行的所有應用程式中的執行階段行為。

偵錯鏈結認證

若要診斷未預期的問題,或是了解鏈式憑證正在執行的動作,請在您的應用程式中啟用記錄日誌。 為了說明目的,假設的無參數形式 DefaultAzureCredential 是用來向 Blob 記憶體帳戶驗證要求。 應用程式會在本機開發環境中執行,開發人員使用 Azure CLI 向 Azure 進行驗證。 應用程式執行時,輸出中會出現以下相關條目:

DEBUG : Identity: Creating DefaultAzureCredential which combines multiple parameterless credentials into a single one.
DefaultAzureCredential is only recommended for the early stages of development, and not for usage in production environment.
Once the developer focuses on the Credentials and Authentication aspects of their application, DefaultAzureCredential needs to be replaced with the credential that is the better fit for the application.
INFO  : Identity: EnvironmentCredential gets created with ClientSecretCredential.
DEBUG : Identity: EnvironmentCredential: 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', and 'AZURE_CLIENT_SECRET' environment variables are set, so ClientSecretCredential with corresponding tenantId, clientId, and clientSecret gets created.
WARN  : Identity: Azure Kubernetes environment is not set up for the WorkloadIdentityCredential credential to work.
DEBUG : Identity: ManagedIdentityCredential: Environment is not set up for the credential to be created with App Service 2019 source.
DEBUG : Identity: ManagedIdentityCredential: Environment is not set up for the credential to be created with App Service 2017 source.
DEBUG : Identity: ManagedIdentityCredential: Environment is not set up for the credential to be created with Cloud Shell source.
DEBUG : Identity: ManagedIdentityCredential: Environment is not set up for the credential to be created with Azure Arc source.
INFO  : Identity: ManagedIdentityCredential will be created with Azure Instance Metadata Service source.
Successful creation does not guarantee further successful token retrieval.
INFO  : Identity: AzureCliCredential created.
Successful creation does not guarantee further successful token retrieval.
INFO  : Identity: DefaultAzureCredential: Created with the following credentials: EnvironmentCredential, WorkloadIdentityCredential, ManagedIdentityCredential, AzureCliCredential.
DEBUG : Identity: DefaultAzureCredential: Failed to get token from EnvironmentCredential: GetToken(): error response: 400 Bad Request

{"error":"invalid_grant","error_description":"AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance. Trace ID: 0000aaaa-11bb-cccc-dd22-eeeeee333333 Correlation ID: aaaa0000-bb11-2222-33cc-444444dddddd Timestamp: 2025-03-07 21:25:44Z","error_codes":[53003],"timestamp":"2025-03-07 21:25:44Z","trace_id":"0000aaaa-11bb-cccc-dd22-eeeeee333333","correlation_id":"aaaa0000-bb11-2222-33cc-444444dddddd","error_uri":"https://login.microsoftonline.com/error?code=53003","suberror":"message_only","claims":"{\"access_token\":{\"capolids\":{\"essential\":true,\"values\":[\"cccc2222-dd33-4444-55ee-666666ffffff\"]}}}"}
WARN  : Identity: WorkloadIdentityCredential authentication unavailable. See earlier WorkloadIdentityCredential log messages for details.
DEBUG : Identity: DefaultAzureCredential: Failed to get token from WorkloadIdentityCredential: WorkloadIdentityCredential authentication unavailable. Azure Kubernetes environment is not set up correctly.
INFO  : Identity: DefaultAzureCredential: Successfully got token from ManagedIdentityCredential. This credential will be reused for subsequent calls.
DEBUG : Identity: DefaultAzureCredential: Saved this credential at index 2 for subsequent calls.

在上列輸出結果中,請注意:

  • EnvironmentCredentialWorkloadIdentityCredentialManagedIdentityCredential (按照順序) 皆無法取得 Microsoft Entra 存取權杖。
  • ManagedIdentityCredential 成功,這由以 "Successfully got token from ManagedIdentityCredential" 開頭的條目所指示。