Simon
Simon

Reputation: 4824

How to solve "ManagedIdentityCredential.GetToken was unable to retrieve an access token." when using Azure ServiceBusTrigger and Managed Identity?

We want to receive service bus messages from our azure service bus using ServiceBusTrigger, locally in Visual Studio 2022. For Authentication, we use Managed Identity.

Context

Microsoft.Azure.Functions.Extensions (1.1.0), Microsoft.Azure.WebJobs.Extensions.ServiceBus (5.15.1), Microsoft.NET.sdk.Functions (4.1.1)

class Function1.cs:

[FunctionName("HandleMessage")]
public static void Run([ServiceBusTrigger("%ServiceBusQueueName%", Connection = ServiceBusNames.ServiceBusConnectionString)] ServiceBusReceivedMessage queueMessage)
{
    var foo = queueMessage;
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusQueueName": "myQueue-myName",
    "ServiceBusConnectionString__fullyQualifiedNamespace": "sb-global-dev.servicebus.windows.net",
  }
}

It is important to add the "logging" to the host.json to get the error message:

{
    "version": "2.0",
    "logging": {
      "LogLevel": {
        "Default": "Information",
        "System": "Warning",
        "Microsoft": "Warning",
        "AP": "Information",
        "Mwp": "Information"
      },
      "ApplicationInsights": {
        "LogLevel": {
          "Default": "Information",
          "System": "Warning",
          "Microsoft": "Warning",
          "AP": "Information",
          "MWP": "Information"
        }
      }
  }
}

.csproj-File:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="5.15.1" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Problem

When we start the function in Visual Studio 2022 via debug mode, we get the following errors in our console output:

enter image description here

enter image description here

enter image description here

Note

Despite the error messages, the ServiceBusTrigger fetches the message from the queue successfully which is confusing.

How can we solve the errors?

Upvotes: 3

Views: 976

Answers (1)

Ikhtesam Afrin
Ikhtesam Afrin

Reputation: 6477

You are getting ManagedIdentityCredential.GetToken was unable to retrieve an access token. error because the local host is not aware about managed identity instead it uses DefaultAzureCredential while working with managed identity locally. You can refer to this github issue wherein @jsquire says below-

enter image description here

  • To mitigate this issue, you can create a Startup class which will have below code in it.
using Azure.Identity;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Azure;

[assembly: FunctionsStartup(typeof(_78584675.Startup))]
namespace _78584675
{
   public class Startup : FunctionsStartup
   {
       public override void Configure(IFunctionsHostBuilder builder)
       {
           builder.Services.AddAzureClients(azureBuilder =>
           {
               var options = new DefaultAzureCredentialOptions
               {
                   ExcludeManagedIdentityCredential = true
               };

               // Configure a new credential to be used by default
               // for all clients that require TokenCredential.

               azureBuilder.UseCredential(new DefaultAzureCredential(options));
           });
       }
   }
}

.csproj-

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <RootNamespace>_78584675</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="5.16.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

enter image description here

If you would like to leverage the benefit of managed identity, then you could consider deploying your function to function app and then add either Azure Service Bus Data Receiver or Azure Service Bus Data Owner RBAC role to your Function App in the Service Bus.

Upvotes: 3

Related Questions