gpt4 book ai didi

Azure.Messaging.ServiceBus 使用系统分配的托管标识创建 ServiceBusClient

转载 作者:行者123 更新时间:2023-12-02 07:18:35 25 4
gpt4 key购买 nike

我正在将服务总线客户端应用程序从 Microsoft.Azure.ServiceBus 迁移到使用当前库 Azure.Messaging.ServiceBus。

该应用程序是在 Windows Azure 中的虚拟机上运行的工作进程。

该虚拟机具有系统分配的托管标识,该标识授予其访问服务总线的权限,我们已经在旧库中成功使用它一年多了。

在旧库上,我们使用此连接字符串创建了一个客户端

Endpoint=sb://MyNamespace.servicebus.windows.net/;Authentication=托管身份

当我将该连接字符串放入 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,因此我们使用基于 key 的连接字符串进行开发,并让 devops 交换正确的产品连接字符串。

更新

根据 Jesse 的回答,托管身份必须通过一个单独的构造函数,该构造函数需要命名空间而不是端点和 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 包和用于连接字符串生成器的命名空间 System.Data.Common。

最佳答案

Azure.Messaging.ServiceBus 包中的客户端仅支持 Azure 门户返回的连接字符串格式。您在连接字符串中包含的 ;Authentication=Managed Identity token 不是已知 token ,因此会被忽略,因此客户端没有执行授权所需的信息。无法通过连接字符串指定托管身份。

要使用托管标识,您将使用接受完全限定命名空间和 TokenCredential 的构造函数重载之一。可以在包 Overview 中找到示例文档。 Azure.Identity 中的任何一个可以使用凭证;您可能想看一下 managed identity Azure.Identity 概述部分。

关于Azure.Messaging.ServiceBus 使用系统分配的托管标识创建 ServiceBusClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71527937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com