如何利用 Service Fabric 應用程式的管理身份來存取 Azure 服務

Service Fabric 應用程式可利用受管理身份存取支援 Microsoft Entra ID 認證的其他 Azure 資源。 應用程式可以取得代表其身份的 存取權杖,該權杖 可由系統指派或使用者指派,並用作「承載」令牌,以驗證自己至另一項服務——也稱為 受保護的資源伺服器。 該憑證代表指派給 Service Fabric 應用程式的身份,且只會發給共享該身份的 Azure 資源(包括 SF 應用程式)。 請參閱 受管身份總覽 文件,了解受管理身份的詳細描述,以及系統指派與使用者指派身份的區別。 本文中將啟用了管理身分識別的 Service Fabric 應用程式稱為 用戶端應用程式。

請參閱一個配套範例應用程式,展示使用系統指派與使用者指派的 Service Fabric 應用程式管理身份 ,搭配 Reliable Services 與容器。

這很重要

受控識別代表 Azure 資源與對應 Microsoft Entra 租用戶中服務主體之間的關聯,而該租用戶與包含此資源的訂用帳戶相關聯。 因此,在 Service Fabric 的情境下,受管理身份僅支援部署為 Azure 資源的應用程式。

這很重要

在使用服務織體應用程式的管理身份之前,用戶端應用程式必須獲得對受保護資源的存取權限。 請參考 支援 Microsoft Entra 認證的 Azure 服務 清單以確認支援情況,然後參考該服務的文件,了解如何授權身份存取感興趣資源的具體步驟。

使用 Azure.Identity 來運用受管理的身分識別

Azure Identity SDK 現在支援 Service Fabric。 使用 Azure.Identity 可讓您更輕鬆地撰寫程式碼來使用 Service Fabric 應用程式受控識別,因為它會處理擷取權杖、快取權杖和伺服器驗證。 在存取大多數 Azure 資源時,代幣的概念是隱藏的。

以下版本提供 Service Fabric 支援,適用於這些語言:

C# 範例:初始化憑證並利用憑證從 Azure Key Vault 取得秘密:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

namespace MyMIService
{
    internal sealed class MyMIService : StatelessService
    {
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            try
            {
                // Load the service fabric application managed identity assigned to the service
                ManagedIdentityCredential creds = new ManagedIdentityCredential();

                // Create a client to keyvault using that identity
                SecretClient client = new SecretClient(new Uri("https://mykv.vault.azure.net/"), creds);

                // Fetch a secret
                KeyVaultSecret secret = (await client.GetSecretAsync("mysecret", cancellationToken: cancellationToken)).Value;
            }
            catch (CredentialUnavailableException e)
            {
                // Handle errors with loading the Managed Identity
            }
            catch (RequestFailedException)
            {
                // Handle errors with fetching the secret
            }
            catch (Exception e)
            {
                // Handle generic errors
            }
        }
    }
}

使用 REST API 取得存取權杖

在啟用受管理身份的叢集中,Service Fabric 執行時會暴露一個本地主機端點,應用程式可利用此端取得存取權杖。 端點可在叢集的每個節點使用,且該節點上的所有實體都能存取。 授權呼叫者可透過呼叫此端點並提供認證碼來取得存取權杖;程式碼由 Service Fabric 執行時針對每個不同的服務碼套件啟動產生,並綁定於承載該服務碼套件的程序生命週期。

具體來說,支援管理身份的 Service Fabric 服務環境將被植入以下變數:

  • 「IDENTITY_ENDPOINT」:對應服務管理身份的 localhost 端點
  • 「IDENTITY_HEADER」:代表當前節點服務的唯一認證碼
  • 「IDENTITY_SERVER_THUMBPRINT」:Service Fabric 管理的身分識別伺服器指紋

這很重要

應用程式碼應將「IDENTITY_HEADER」環境變數的值視為敏感資料——不應被記錄或以其他方式散布。 認證碼在本地節點外或服務承載程序終止後無效,但它代表服務結構服務的身份,因此應以與存取權杖本身相同的謹慎處理。

要取得代幣,客戶端需執行以下步驟:

  • 形成一個 URI 的方法是將受管身份端點(IDENTITY_ENDPOINT 值)與 API 版本以及令牌所需的資源(受眾)串接起來。
  • 為指定的 URI 建立一個 GET http(s) 請求
  • 新增適當的伺服器憑證驗證邏輯
  • 將驗證碼(IDENTITY_HEADER值)作為請求標頭加入
  • 提交請求

成功的回應包含代表存取權杖的 JSON 有效載荷,以及描述該權杖的元資料。 失敗的回應也會包含失敗的說明。 關於錯誤處理的更多細節請見下方。

存取權杖會由 Service Fabric 在不同層級(節點、叢集、資源提供者服務)快取,因此成功回應不一定代表該權杖是直接回應使用者應用程式的請求而發出。 權杖的快取時間會短於其存留期,因此應用程式一定會收到有效的權杖。 建議應用程式程式碼自行快取所取得的任何存取權杖;快取索引鍵應包含對象的衍生值。

範例要求:

GET 'https://localhost:2377/metadata/identity/oauth2/token?api-version=2019-07-01-preview&resource=https://vault.azure.net/' HTTP/1.1 Secret: aaaabbbb-0000-cccc-1111-dddd2222eeee

where:

元素 說明
GET HTTP 動詞,指示要從終端節點檢索數據。 在本例中,為 OAuth 訪問令牌。
https://localhost:2377/metadata/identity/oauth2/token 服務織體應用程式的管理身份端點,透過IDENTITY_ENDPOINT環境變數提供。
api-version 一個查詢字串參數,指定管理身份令牌服務的 API 版本;目前唯一被接受的值為 2019-07-01-preview,且可能會變動。
resource 查詢字串參數,指示目標資源的App ID URI。 這會反映為已發行權杖的 aud 宣告 (對象)。 此範例請求一個令牌以存取 Azure Key Vault 的 App ID URI https://vault.azure.net/.
Secret HTTP 請求標頭欄位,這是 Service Fabric 管理身份憑證服務(Managed Identity Token Service)對 Service Fabric 服務用以驗證呼叫者所要求的。 此值由 SF 執行時透過環境變數提供IDENTITY_HEADER。

範例回應:

HTTP/1.1 200 OK
Content-Type: application/json
{
    "token_type":  "Bearer",
    "access_token":  "eyJ0eXAiO...",
    "expires_on":  1565244611,
    "resource":  "https://vault.azure.net/"
}

where:

元素 說明
token_type 權杖的類型;在此案例中,是「Bearer」存取權杖,表示此權杖的出示者「Bearer」就是權杖的目標主體。
access_token 要求的存取憑證。 呼叫受保護的 REST API 時,令牌會內嵌在 Authorization 要求標頭欄位中作為「持有人」令牌,讓 API 驗證呼叫端。
expires_on 存取權杖到期的時間戳記;以自「1970-01-01T0:0:0Z UTC」起算的秒數表示,並對應至權杖的 exp 宣告。 在此情況下,該令牌於 2019-08-08T06:10:11+00:00(RFC 3339 中)到期
resource 發行存取權杖所對應的資源,是透過要求的 resource 查詢字串參數指定;此項目對應至權杖的 「aud」 宣告。

使用 C# 取得存取權杖

上述在 C# 中變成:

namespace Azure.ServiceFabric.ManagedIdentity.Samples
{
    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using Newtonsoft.Json;

    /// <summary>
    /// Type representing the response of the SF Managed Identity endpoint for token acquisition requests.
    /// </summary>
    [JsonObject]
    public sealed class ManagedIdentityTokenResponse
    {
        [JsonProperty(Required = Required.Always, PropertyName = "token_type")]
        public string TokenType { get; set; }

        [JsonProperty(Required = Required.Always, PropertyName = "access_token")]
        public string AccessToken { get; set; }

        [JsonProperty(PropertyName = "expires_on")]
        public string ExpiresOn { get; set; }

        [JsonProperty(PropertyName = "resource")]
        public string Resource { get; set; }
    }

    /// <summary>
    /// Sample class demonstrating access token acquisition using Managed Identity.
    /// </summary>
    public sealed class AccessTokenAcquirer
    {
        /// <summary>
        /// Acquire an access token.
        /// </summary>
        /// <returns>Access token</returns>
        public static async Task<string> AcquireAccessTokenAsync()
        {
            var managedIdentityEndpoint = Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT");
            var managedIdentityAuthenticationCode = Environment.GetEnvironmentVariable("IDENTITY_HEADER");
            var managedIdentityServerThumbprint = Environment.GetEnvironmentVariable("IDENTITY_SERVER_THUMBPRINT");
            // Latest api version, 2019-07-01-preview is still supported.
            var managedIdentityApiVersion = Environment.GetEnvironmentVariable("IDENTITY_API_VERSION");
            var managedIdentityAuthenticationHeader = "secret";
            var resource = "https://management.azure.com/";

            var requestUri = $"{managedIdentityEndpoint}?api-version={managedIdentityApiVersion}&resource={HttpUtility.UrlEncode(resource)}";

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri);
            requestMessage.Headers.Add(managedIdentityAuthenticationHeader, managedIdentityAuthenticationCode);
            
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, certChain, policyErrors) =>
            {
                // Do any additional validation here
                if (policyErrors == SslPolicyErrors.None)
                {
                    return true;
                }
                return 0 == string.Compare(cert.GetCertHashString(), managedIdentityServerThumbprint, StringComparison.OrdinalIgnoreCase);
            };

            try
            {
                var response = await new HttpClient(handler).SendAsync(requestMessage)
                    .ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                var tokenResponseString = await response.Content.ReadAsStringAsync()
                    .ConfigureAwait(false);

                var tokenResponseObject = JsonConvert.DeserializeObject<ManagedIdentityTokenResponse>(tokenResponseString);

                return tokenResponseObject.AccessToken;
            }
            catch (Exception ex)
            {
                string errorText = String.Format("{0} \n\n{1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : "Acquire token failed");

                Console.WriteLine(errorText);
            }

            return String.Empty;
        }
    } // class AccessTokenAcquirer
} // namespace Azure.ServiceFabric.ManagedIdentity.Samples

使用管理身份從服務織體應用程式存取金鑰庫

本範例基於上述內容,示範如何利用管理身份存取存放在金鑰庫中的秘密。

        /// <summary>
        /// Probe the specified secret, displaying metadata on success.  
        /// </summary>
        /// <param name="vault">vault name</param>
        /// <param name="secret">secret name</param>
        /// <param name="version">secret version id</param>
        /// <returns></returns>
        public async Task<string> ProbeSecretAsync(string vault, string secret, string version)
        {
            // initialize a KeyVault client with a managed identity-based authentication callback
            var kvClient = new Microsoft.Azure.KeyVault.KeyVaultClient(new Microsoft.Azure.KeyVault.KeyVaultClient.AuthenticationCallback((a, r, s) => { return AuthenticationCallbackAsync(a, r, s); }));

            Log(LogLevel.Info, $"\nRunning with configuration: \n\tobserved vault: {config.VaultName}\n\tobserved secret: {config.SecretName}\n\tMI endpoint: {config.ManagedIdentityEndpoint}\n\tMI auth code: {config.ManagedIdentityAuthenticationCode}\n\tMI auth header: {config.ManagedIdentityAuthenticationHeader}");
            string response = String.Empty;

            Log(LogLevel.Info, "\n== {DateTime.UtcNow.ToString()}: Probing secret...");
            try
            {
                var secretResponse = await kvClient.GetSecretWithHttpMessagesAsync(vault, secret, version)
                    .ConfigureAwait(false);

                if (secretResponse.Response.IsSuccessStatusCode)
                {
                    // use the secret: secretValue.Body.Value;
                    response = String.Format($"Successfully probed secret '{secret}' in vault '{vault}': {PrintSecretBundleMetadata(secretResponse.Body)}");
                }
                else
                {
                    response = String.Format($"Non-critical error encountered retrieving secret '{secret}' in vault '{vault}': {secretResponse.Response.ReasonPhrase} ({secretResponse.Response.StatusCode})");
                }
            }
            catch (Microsoft.Rest.ValidationException ve)
            {
                response = String.Format($"encountered REST validation exception 0x{ve.HResult.ToString("X")} trying to access '{secret}' in vault '{vault}' from {ve.Source}: {ve.Message}");
            }
            catch (KeyVaultErrorException kvee)
            {
                response = String.Format($"encountered KeyVault exception 0x{kvee.HResult.ToString("X")} trying to access '{secret}' in vault '{vault}': {kvee.Response.ReasonPhrase} ({kvee.Response.StatusCode})");
            }
            catch (Exception ex)
            {
                // handle generic errors here
                response = String.Format($"encountered exception 0x{ex.HResult.ToString("X")} trying to access '{secret}' in vault '{vault}': {ex.Message}");
            }

            Log(LogLevel.Info, response);

            return response;
        }

        /// <summary>
        /// KV authentication callback, using the application's managed identity.
        /// </summary>
        /// <param name="authority">The expected issuer of the access token, from the KV authorization challenge.</param>
        /// <param name="resource">The expected audience of the access token, from the KV authorization challenge.</param>
        /// <param name="scope">The expected scope of the access token; not currently used.</param>
        /// <returns>Access token</returns>
        public async Task<string> AuthenticationCallbackAsync(string authority, string resource, string scope)
        {
            Log(LogLevel.Verbose, $"authentication callback invoked with: auth: {authority}, resource: {resource}, scope: {scope}");
            var encodedResource = HttpUtility.UrlEncode(resource);

            // This sample does not illustrate the caching of the access token, which the user application is expected to do.
            // For a given service, the caching key should be the (encoded) resource uri. The token should be cached for a period
            // of time at most equal to its remaining validity. The 'expires_on' field of the token response object represents
            // the number of seconds from Unix time when the token will expire. You may cache the token if it will be valid for at
            // least another short interval (1-10s). If its expiration will occur shortly, don't cache but still return it to the 
            // caller. The MI endpoint will not return an expired token.
            // Sample caching code:
            //
            // ManagedIdentityTokenResponse tokenResponse;
            // if (responseCache.TryGetCachedItem(encodedResource, out tokenResponse))
            // {
            //     Log(LogLevel.Verbose, $"cache hit for key '{encodedResource}'");
            //
            //     return tokenResponse.AccessToken;
            // }
            //
            // Log(LogLevel.Verbose, $"cache miss for key '{encodedResource}'");
            //
            // where the response cache is left as an exercise for the reader. MemoryCache is a good option, albeit not yet available on .net core.

            var requestUri = $"{config.ManagedIdentityEndpoint}?api-version={config.ManagedIdentityApiVersion}&resource={encodedResource}";
            Log(LogLevel.Verbose, $"request uri: {requestUri}");

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri);
            requestMessage.Headers.Add(config.ManagedIdentityAuthenticationHeader, config.ManagedIdentityAuthenticationCode);
            Log(LogLevel.Verbose, $"added header '{config.ManagedIdentityAuthenticationHeader}': '{config.ManagedIdentityAuthenticationCode}'");

            var response = await httpClient.SendAsync(requestMessage)
                .ConfigureAwait(false);
            Log(LogLevel.Verbose, $"response status: success: {response.IsSuccessStatusCode}, status: {response.StatusCode}");

            response.EnsureSuccessStatusCode();

            var tokenResponseString = await response.Content.ReadAsStringAsync()
                .ConfigureAwait(false);

            var tokenResponse = JsonConvert.DeserializeObject<ManagedIdentityTokenResponse>(tokenResponseString);
            Log(LogLevel.Verbose, "deserialized token response; returning access code..");

            // Sample caching code (continuation):
            // var expiration = DateTimeOffset.FromUnixTimeSeconds(Int32.Parse(tokenResponse.ExpiresOn));
            // if (expiration > DateTimeOffset.UtcNow.AddSeconds(5.0))
            //    responseCache.AddOrUpdate(encodedResource, tokenResponse, expiration);

            return tokenResponse.AccessToken;
        }

        private string PrintSecretBundleMetadata(SecretBundle bundle)
        {
            StringBuilder strBuilder = new StringBuilder();

            strBuilder.AppendFormat($"\n\tid: {bundle.Id}\n");
            strBuilder.AppendFormat($"\tcontent type: {bundle.ContentType}\n");
            strBuilder.AppendFormat($"\tmanaged: {bundle.Managed}\n");
            strBuilder.AppendFormat($"\tattributes:\n");
            strBuilder.AppendFormat($"\t\tenabled: {bundle.Attributes.Enabled}\n");
            strBuilder.AppendFormat($"\t\tnbf: {bundle.Attributes.NotBefore}\n");
            strBuilder.AppendFormat($"\t\texp: {bundle.Attributes.Expires}\n");
            strBuilder.AppendFormat($"\t\tcreated: {bundle.Attributes.Created}\n");
            strBuilder.AppendFormat($"\t\tupdated: {bundle.Attributes.Updated}\n");
            strBuilder.AppendFormat($"\t\trecoveryLevel: {bundle.Attributes.RecoveryLevel}\n");

            return strBuilder.ToString();
        }

        private enum LogLevel
        {
            Info,
            Verbose
        };

        private void Log(LogLevel level, string message)
        {
            if (level != LogLevel.Verbose
                || config.DoVerboseLogging)
            {
                Console.WriteLine(message);
            }
        }

錯誤處理

HTTP 回應標頭中的「狀態碼」欄位表示請求的成功狀態;「200 OK」狀態表示成功,回應會包含上述存取權杖。 以下是可能錯誤回應的簡短列舉。

狀態代碼 錯誤原因 如何處理
404 未找到。 驗證碼未知,或是應用程式沒有被分配管理身份。 修正應用程式設定或代幣取得代碼。
429 請求太多。 頻寬限制已達到,由 Microsoft Entra ID 或 SF 設定。 使用 Exponential Backoff 重試。 請參閱下面的指南。
4xx 請求錯誤。 一個或多個請求參數不正確。 不要重試。 檢查錯誤詳細資訊以瞭解更多資訊。 4xx 錯誤是設計時錯誤。
5xx 服務錯誤。 管理身份子系統(Managed Identity Subsystem)或 Microsoft Entra ID 回傳了一個暫時錯誤。 不久後可以安全重試。 重試時,您可能會遇到節流狀況 (429)。

若發生錯誤,對應的 HTTP 回應主體會包含一個包含錯誤細節的 JSON 物件:

元素 說明
字碼 錯誤碼。
correlationId 一個可用於除錯的關聯 ID。
訊息 錯誤的詳細描述。 錯誤描述可能隨時更改。 不要只依賴錯誤訊息本身。

範例錯誤:

{"error":{"correlationId":"aaaa0000-bb11-2222-33cc-444444dddddd","code":"SecretHeaderNotFound","message":"Secret is not found in the request headers."}}

以下是管理身份特有的典型 Service Fabric 錯誤列表:

Code Message 說明
SecretHeaderNotFound 要求標頭中找不到祕密。 申請時沒有附上驗證碼。
ManagedIdentityNotFound 未找到指定應用程式主機的管理身份。 應用程式沒有身份,或是驗證碼未知。
ArgumentNullOrEmpty 參數「resource」不應該是 null 或空字串。 請求中沒有提供資源(受眾)。
InvalidApiVersion API 版本的 '' 不被支援。 支援版本為「2019-07-01-preview」。 請求 URI 中指定缺失或不支援的 API 版本。
內部伺服器錯誤 發生錯誤。 在管理身份子系統中出現錯誤,該錯誤可能發生在 Service Fabric 堆疊之外。 最可能的原因是資源值指定錯誤(檢查後面是否有 '/'?)

重試指南

通常唯一可重試的錯誤代碼是 429(請求過多);內部伺服器錯誤/5xx 錯誤代碼可能可重試,但原因可能是永久性的。

限制適用於對受管理的身分識別子系統進行呼叫的次數,特別是「上游」相依項目(受管理的身分識別 Azure 服務,或安全令牌服務)。 Service Fabric 會在管線中的各個層級快取權杖,但由於相關元件具有分散式特性,因此呼叫端可能會遇到不一致的節流回應,也就是在某個應用程式節點/執行個體上受到節流,但在另一個節點上為相同識別要求權杖時卻不會。當節流狀況設定後,相同應用程式的後續要求可能會失敗,並傳回 HTTP 狀態碼 429 (要求過多),直到該狀況解除為止。

建議因節流而失敗的要求,採用下列指數輪詢退避方式重試:

呼叫索引 接收429狀態碼後的行動
1 等一秒再試一次
2 等兩秒再試一次
3 等4秒再試一次
4 等 8 秒再試一次
4 等 8 秒再試一次
5 等16秒再試一次

Azure 服務的資源識別碼

請參閱 支援 Microsoft Entra 認證的 Azure 服務 ,了解支援 Microsoft Entra ID 及其相應資源 ID 的資源清單。

下一步