从Azure App Service向Service Bus队列发消息的权限认证问题
我有一个App Service(REST API),作为概念验证,尝试向Service Bus队列发送消息。
我添加了Microsoft身份提供者并禁用了身份验证(希望服务无需身份验证),同时为App Service创建了服务主体。随后在Service Bus队列中添加了Azure Service Bus Data Sender角色的角色分配,关联的是添加身份提供者时生成的服务主体(包含应用注册和企业应用对象)。
我的应用代码如下:
var ns = configuration["namespace"]; var queueName = configuration["queue"]; // name of your Service Bus queue // the client that owns the connection and can be used to create senders and receivers await using (ServiceBusClient client = new ServiceBusClient(ns, new DefaultAzureCredential(), clientOptions)) // the sender used to publish messages to the queue await using (ServiceBusSender sender = client.CreateSender(queueName)) { ServiceBusMessage msg = new ServiceBusMessage("Test") { ContentType = singleStream.Headers.ContentType.ToString(), CorrelationId = correlationID, Subject = "Submission", }; msg.ApplicationProperties.Add("Context.ContentType", contextData.Headers.ContentType.ToString()); msg.ApplicationProperties.Add("Message.ContentType", messageData.Headers.ContentType.ToString()); msg.ApplicationProperties.Add("Attachment.Count", 0); //using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync(); await sender.SendMessageAsync(msg); }
运行后出现异常:
DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information.
EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information.
ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.
- Visual Studio Token provider can't be accessed at D:\DWASFiles\Sites\MyService-ASE\LocalAppData.IdentityService\AzureServiceAuth\tokenprovider.json
- Azure CLI not installed
- Az.Account module >= 2.2.0 is not installed.
我猜测是凭证传递或App Service服务主体配置有问题,想授予服务向队列发送消息的权限,但找不到问题根源。
编辑1
我尝试为App Service启用系统分配托管身份,然后为队列添加角色分配并选择该托管身份作为成员。代码改用ManagedIdentityCredential替代DefaultAzureCredential,但出现新错误:
Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://mysericebus-sbus.servicebus.windows.net/myqueue-sbq'. TrackingId:82d9b43f639c4a0c990e1581de8aa5db_G21, SystemTracker:gateway7, Timestamp:2023-03-15T18:57:09
For troubleshooting information, see the service bus exceptions guide.
编辑2
我将角色分配添加到Service Bus命名空间而非直接添加到队列后,功能正常工作。但这样命名空间内的所有队列都会继承该角色分配,导致托管身份拥有向命名空间内所有队列发送消息的权限,权限范围过宽。
内容的提问来源于stack exchange,提问作者Jeremy

