Search code examples
triggersazure-functionsazureservicebusazure-managed-identity

How to use Azure Managed Identity in Azure Function to access Service Bus with a trigger?


I have created a ServiceBus namespace in Azure, along with a topic and a subscription. I also have a simple Azure version 1 function that triggers on a received topic in the ServiceBus, like this:

[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}");
}

The function triggers nicely for the topics in the ServiceBus when I define the connection string in functions Application Settings by using Shared Access Policy for topic, like this:

Endpoint=sb://MyNamespace.servicebus.windows.net/;SharedAccessKeyName=mypolicy;SharedAccessKey=UZ...E0=

Now, instead of Shared Access Keys, I would like to use Managed Service Identity (MSI) for accessing the ServiceBus. According to this (https://learn.microsoft.com/en-us/azure/active-directory/managed-service-identity/services-support-msi) it should be possible, unless I have misunderstood something. I haven't managed to get it working though.

What I tried, was to

  • set the Managed Service Identity "On" for my function in Azure portal
  • give Owner role for the function in ServiceBus Access Control section in Azure Portal
  • set the connection string for MyFunction like this: Endpoint=sb://MyNamespace.servicebus.windows.net/

The function is not triggering in this set-up, so what am I missing or what am I doing wrong? I'd be grateful for any advice to help me get further. Thanks.


Solution

  • what am I missing or what am I doing wrong?

    You may mix up with MSI and Shared Access Policy. They are using different provider to access to Azure ServiceBus. You could just use ConnectionString or just use MSI to authenticate.

    When you use Managed Service Identity (MSI) to authenticate, you need to create a token provider for the managed service identity with the following code.

    TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.ServiceBusAudience)
    

    This TokenProvider's implementation uses the AzureServiceTokenProvider found in the Microsoft.Azure.Services.AppAuthentication library. AzureServiceTokenProvider will follow a set number of different methods, depending on the environment, to get an access token. And then initialize client to operate the ServiceBus. For more details, you could refer to this article.

    When you use the ServiceBus's ConnectionString to access which in tiurn uses the Shared Access Token (SAS) token provider, so you can operate directly.