我正在从 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 的回答之后,托管身份必须通过一个单独的构造函数,该构造函数需要一个命名空间而不是一个端点和一个 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
令牌不是已知令牌,因此会被忽略,因此客户端没有执行授权所需的信息。无法通过连接字符串指定托管标识。
要使用托管标识,您将使用接受完全限定命名空间和
TokenCredential
的构造函数重载之一。可以在包 Overview 文档中找到一个示例。可以使用任何 Azure.Identity 凭据;您可能想看看 Azure.Identity
概述的 managed identity部分。
我使用此文档使用托管身份连接到 Azure 服务总线。
不需要连接字符串或客户端密码。授权由
DefaultAzureCredentials()
处理,它与系统分配的托管身份很好地配合。
参考: