簡體   English   中英

Azure.Messaging.ServiceBus 使用系統分配的托管標識創建 ServiceBusClient

[英]Azure.Messaging.ServiceBus Create a ServiceBusClient using a System Assigned Managed Identity

我正在從 Microsoft.Azure.ServiceBus 遷移服務總線客戶端應用程序以使用當前庫 Azure.Messaging.ServiceBus。

該應用程序是運行在windows azure虛擬機上的一個Worker Process。

VM 有一個系統分配的托管身份,授予它訪問服務總線的權限,我們已經成功地將它與舊庫一起使用了一年多。

在舊庫上,我們使用此連接字符串創建了一個客戶端

Endpoint=sb://MyNamespace.servicebus.windows.net/;Authentication=Managed Identity

當我將該連接字符串放入 Azure.Messaging.ServiceBus.ServiceBusClient 的構造函數時,出現以下錯誤

The connection string used for an Service Bus client must specify the Service Bus namespace host and either a Shared Access Key (both the name and value) OR a Shared Access Signature to be valid. (Parameter 'connectionString')

我一直在瀏覽文件一段時間,但沒有任何進展。 有沒有辦法使這項工作?

理想情況下,我會繼續使用連接字符串——開發人員機器沒有系統分配的 ID,因此我們使用基於密鑰的連接字符串進行開發,並讓 devops 交換正確的產品連接字符串。

更新

在 Jesse 的回答之后,托管身份必須通過一個單獨的構造函數達到 go,該構造函數需要一個命名空間而不是端點和 ManagedIdentityCredential 的一個實例。

正如我提到的,並非我們部署的所有環境都管理過時的身份,有些環境需要基於 SharedAccessKey 的連接字符串。

我使用工廠方法來解析連接字符串並調用正確的構造函數重載,而不是在我們的構建過程中引入新的“身份類型”配置參數。 它是一個托管身份,它從端點設置中提取命名空間。

我希望它對其他人有用

        private static ServiceBusClient CreateServiceBusClient(string connectionString)
        {
            var cs = new DbConnectionStringBuilder();
            cs.ConnectionString = connectionString;
            if (cs.ContainsKey("Authentication") &&
                "Managed Identity".Equals(cs["Authentication"].ToString(), StringComparison.OrdinalIgnoreCase))
            {
                string endpoint = cs["Endpoint"].ToString() ?? String.Empty;
                if (endpoint.StartsWith(@"sb://", StringComparison.OrdinalIgnoreCase)) endpoint = endpoint.Substring(5);
                if (endpoint.EndsWith(@"/")) endpoint = endpoint.Substring(0, endpoint.Length - 1);
                return new ServiceBusClient(endpoint, new ManagedIdentityCredential());
            }

            return new ServiceBusClient(connectionString);
        }

它需要 Azure.Identity package 和連接字符串生成器的命名空間 System.Data.Common。

Azure.Messaging.ServiceBus package 中的客戶端僅支持 Azure 門戶返回的格式的連接字符串。 您在連接字符串中包含的;Authentication=Managed Identity令牌不是已知令牌並被忽略,因此客戶端沒有執行授權所需的信息。 無法通過連接字符串指定托管標識。

要使用托管標識,您將使用接受完全限定命名空間和TokenCredential的構造函數重載之一。 可以在 package 概述文檔中找到一個示例。 可以使用Azure.Identity憑證中的任何一個; 您可能想看看Azure.Identity概述的托管身份部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM