I Have Azure Ad application MyApplication which contain 10 to 12 microservices. In expose api i have already
I have created my user custom identity to access azure ad app
I need to use my user manage identity to generate token for my all microservice beside my azure add app below is my scope api://axxxxxxxxxx/AllowAnonymus
string clientId = "XXXX"; // The Client ID of the user assigned identity
AccessToken token = await new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = clientId
})
.GetTokenAsync(
new TokenRequestContext(
new[] { "api://axxxxxxxxxx/AllowAnonymus" }
));
I m not able generate token with this code. any one have idea
Note that: It is not possible to assign delegated permissions to Azure managed identity. Refer this SO Thread by juunas.
If you are adding scope under Expose an API tab, then it is a delegated scope:
And hence you cannot assign this kind of permission to user managed assigned and generate token.
As a workaround, you can instead create app roles in the Microsoft Entra application:
Now assign this app role to User managed identity:
Connect-AzureAD
New-AzureADServiceAppRoleAssignment -ObjectId MIObjectID -Id AppRoleID -PrincipalId MIObjectID -ResourceId MicrosoftEntraServicrPrincipalObjID
ObjectID and PrincipalId will be:
Go to Enterprise application -> Search your managed identity (with filter as All applications):
ResourceID is the Microsoft Entra Service principal objectID:
Now, you can generate token by using below code:
using System;
using Azure.Identity;
using Azure.Core;
class Program
{
static async Task Main(string[] args)
{
string clientId = "XXX"; // The Client ID of the user assigned identity
AccessToken token = await new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = clientId
})
.GetTokenAsync(
new TokenRequestContext(
new[] { "api://XXX/.default" }
));
Console.WriteLine(token.Token);
}
}
Note that: Managed Identity cannot be used locally because the security boundary of the managed identity is the Azure resource to which it is attached to.