Azure Service Bus managed identity in Visual Studio returning 401 - Token issuer is invalid

Solution 1:

If you use DefaultAzureCredential to auth, it will try several credential types to auth as mentioned here, one of them is VisualStudioCredential, but it will auth to the home AAD tenant of the user logged in VS, in your case, I suppose the service bus is in a subscription which is not under the home tenant of the user.

I can also reproduce your issue on my side.

enter image description here

To solve the issue, just use VisualStudioCredential directly, then simply specify the TenantId via VisualStudioCredentialOptions, then it will work fine.

Sample:

To find the TenantId, just navigate to the Azure Active Directory which the subscription of your service bus located.

enter image description here

TokenCredential tokenCredential = new VisualStudioCredential(new VisualStudioCredentialOptions {TenantId = "xxxxxxx" });
ServiceBusClient client = new ServiceBusClient("xxx.servicebus.windows.net", tokenCredential);

enter image description here

Solution 2:

Since I have access to several different tenants, Visual Studio sometimes gets confused. Another way you can handle this is to continue to use the DefaultAzureCredential, but to give Visual Studio a hint about which tenant to use.
enter image description here First left click the your project and examine the properties and then:

  1. Left-click "Debug"
  2. Left-click the "Add" button to add an environment variable
  3. For name use "AZURE_TENANT_ID" and for value use your tenant id. Yes, that is a bogus tenant id in the picture :-)

Reference

  • https://docs.microsoft.com/en-us/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet
  • https://damienbod.com/2020/10/09/using-key-vault-certificates-with-microsoft-identity-web-and-asp-net-core-applications/

Solution 3:

Specify the exact tenant id by adding the following key to local.settings.json.

"AZURE_TENANT_ID": "your tenant id"

enter image description here

I tried to create an azure function that receives messages from a service bus queue using a managed identity trigger and it worked for me. enter image description here