繁体   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