如何在 Azure Function 中使用 Azure 托管标识通过触发器访问服务总线?

Yuh*_*his 9 triggers azureservicebus azure-functions azure-managed-identity

我在 Azure 中创建了一个 ServiceBus 命名空间,以及一个主题和一个订阅。我还有一个简单的 Azure 版本 1 函数,它触发 ServiceBus 中接收到的主题,如下所示:

[FunctionName("MyServiceBusTriggerFunction")]
public static void Run([ServiceBusTrigger("myTopic", "mySubscription", Connection = "MyConnection")]string mySbMsg, TraceWriter log)
{
    log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
Run Code Online (Sandbox Code Playgroud)

当我使用主题的共享访问策略在函数应用程序设置中定义连接字符串时,该函数可以很好地触发 ServiceBus 中的主题,如下所示:

Endpoint=sb://MyNamespace.servicebus.windows.net/;SharedAccessKeyName=mypolicy;SharedAccessKey=UZ...E0=
Run Code Online (Sandbox Code Playgroud)

现在,我想使用托管服务标识 (MSI) 来访问 ServiceBus,而不是共享访问密钥。根据这个(https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/services-support-msi)应该是可能的,除非我误解了一些东西。我还没有设法让它工作。

我试过的是

  • 在 Azure 门户中为我的函数设置托管服务标识“开启”
  • 为 Azure 门户中 ServiceBus 访问控制部分中的函数赋予所有者角色
  • 像这样设置 MyFunction 的连接字符串:Endpoint=sb://MyNamespace.servicebus.windows.net/

该功能未在此设置中触发,所以我错过了什么或我做错了什么?如果您有任何建议可以帮助我走得更远,我将不胜感激。谢谢。

Ily*_*dik 9

更新Microsoft.Azure.WebJobs.Extensions.ServiceBus版本 5.x

现在这里有该软件包最新版本的官方文档。

{
  "Values": {
    "<connection_name>__fullyQualifiedNamespace": "<service_bus_namespace>.servicebus.windows.net"
  }
}
Run Code Online (Sandbox Code Playgroud)

之前的回答

现在这实际上似乎是可能的,至少对我来说效果很好。您需要使用此连接字符串:

Endpoint=sb://service-bus-namespace-name.servicebus.windows.net/;Authentication=ManagedIdentity
Run Code Online (Sandbox Code Playgroud)

我实际上没有在 Microsoft 网站上找到任何有关此内容的文档,而是在此处的博客中找到。

Microsoft 确实有关于您可以使用的角色以及如何将它们限制在此处的范围的文档。例子:

az role assignment create \
    --role $service_bus_role \
    --assignee $assignee_id \
    --scope /subscriptions/$subscription_id/resourceGroups/$resource_group/providers/Microsoft.ServiceBus/namespaces/$service_bus_namespace/topics/$service_bus_topic/subscriptions/$service_bus_subscription
Run Code Online (Sandbox Code Playgroud)


Joe*_*Cai 4

我错过了什么或者我做错了什么?

您可能会混淆 MSI 和共享访问策略。它们使用不同的提供商来访问 Azure servicebus。您可以仅使用连接字符串或仅使用 MSI 进行身份验证。

当您使用Managed Service Identity(MSI) 进行身份验证时,您需要使用以下代码为托管服务身份创建令牌提供程序。

TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience)

TokenProvider的实现使用AzureServiceTokenProviderMicrosoft.Azure.Services.AppAuthentication库中找到的。AzureServiceTokenProvider根据环境,将遵循一系列不同的方法来获取访问令牌。然后初始化客户端来操作servicebus。欲了解更多详情,您可以参考这篇文章

当您使用servicebus连接字符串来访问时,它使用共享访问令牌(SAS)令牌提供程序,因此您可以直接进行操作。

  • 具有 ServiceBusTrigger 的 Azure Function 需要连接字符串作为参数。当它被触发运行时,它已经需要被授权。那时为 MSI 创建 TokenProvider 为时已晚,所以看起来我无法使用它。我认为 MSI 应该在幕后处理访问令牌,但事实似乎并非如此。正确的? (4认同)
  • 其实就是这样!您无法使用 MSI 来验证服务总线触发功能。 (2认同)