Application roles with Entra ID
此内容尚不支持你的语言。
Application roles appear in the roles claim of tokens that Microsoft Entra ID issues for your API, so the API can tell a caller that holds Orders.Read from one that doesn’t. They’re separate from delegated scopes, from consent, and from Azure role-based access control (RBAC) roles. For the scope-based model, see Expose and call APIs.
Aspire declares roles on registrations that it creates, and it can assign a role to a managed identity when you publish. It doesn’t assign roles to users, groups, or applications, including client registrations in your AppHost.
Declare application roles
Section titled “Declare application roles”Use WithAppRole to declare a role on a registration that Aspire creates. Declaring a role doesn’t assign it to anyone.
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const entraApi = await builder.addEntraIdApplication("entra-api") .withAppRole("User", "User", "Can use the API.") .withAppRole("Admin", "Administrator", "Can administer the API.", { allowedMemberTypes: ["User", "Application"], });
const apiService = await builder.addDotnetProject("apiservice", "../Api/Api.csproj");await apiService.withReference(entraApi);
await builder.build().run();using Aspire.Hosting.Azure;
var builder = DistributedApplication.CreateBuilder(args);
var entraApi = builder.AddEntraIdApplication("entra-api") .WithAppRole(new EntraIdAppRole("User", "User", "Can use the API.")) .WithAppRole(new EntraIdAppRole("Admin", "Administrator", "Can administer the API.", ["User", "Application"]));
builder.AddDotnetProject("apiservice", "../Api/Api.csproj") .WithReference(entraApi);
// After adding all resources, run the app...builder.Build().Run();In TypeScript, you pass the values of the role to withAppRole and the optional settings in an options object. In C#, you create an EntraIdAppRole and pass it to WithAppRole.
| Setting | Description |
|---|---|
value | The value in the roles claim, such as Admin. It must be unique for the application. |
displayName | The name that the Microsoft Entra admin center shows. |
description | The text that assignment and consent experiences show. |
allowedMemberTypes | Passed through to Microsoft Graph, such as User or Application. Include Application to let managed identities hold the role. The default is User. |
id | Optional. When omitted, the ID is derived from the resource name and role value, so changing either creates a different role. |
isEnabled | Whether the role can be assigned. The default is true. |
A role value can have at most 120 characters, can’t start with a period, and can contain only ASCII letters, digits, and the punctuation that Microsoft Graph allows. Aspire rejects spaces and quotation marks when the call runs. Two roles on one registration can’t share an ID.
Understand how deployments update roles
Section titled “Understand how deployments update roles”Each deployment replaces the registration’s roles with the roles the AppHost declares. Include every role that you want to keep, including roles added outside the AppHost. Leaving out an enabled role fails the deployment with CannotDeleteOrUpdateEnabledEntitlement, and leaving out a disabled role deletes it. If the AppHost declares no roles, Aspire leaves the registration’s roles unchanged.
Retire a role
Section titled “Retire a role”Retire a role in two steps.
- Remove the
PublishWithAppRoleAssignmentcalls for the role, setisEnabledtofalse, and leave the role declared. Deploy. - Remove the role from the AppHost and deploy again, while other roles remain declared.
A disabled role can’t be assigned to anyone new. Microsoft Entra ID keeps issuing it in tokens for existing assignments, so disabling isn’t access revocation. Remove the existing assignments separately.
Removing the last declared role from the AppHost doesn’t delete it from the registration. Keep it declared with isEnabled set to false, or delete it in the Microsoft Entra admin center.
Assign roles to managed identities
Section titled “Assign roles to managed identities”PublishWithAppRoleAssignment grants a user-assigned managed identity an application role on an API registration that Aspire creates. A caller then authenticates directly as its managed identity, so it needs no registration of its own and no federated credential.
The role must be declared, enabled, and allow Application members. Declare the role with WithAppRole before you call PublishWithAppRoleAssignment. Aspire creates assignments only when you publish, not when you run locally.
You can pass the managed identity or the app that uses it. When you pass an app, Aspire uses its attached identity. If the app has none, a supported Azure deployment environment creates one. In C#, separate overloads accept the identity or the app. In TypeScript, one method accepts either.
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment("env");
const callerIdentity = await builder.addAzureUserAssignedIdentity("caller-identity");
const worker = await builder.addDotnetProject("worker", "../Worker/Worker.csproj");await worker.withAzureUserAssignedIdentity(callerIdentity);// The caller requests a token for the API's application ID URI.await worker.withEnvironment("ORDERS_API_SCOPE", "api://orders/.default");
const entraApi = await builder.addEntraIdApplication("entra-api") .withApplicationIdUri({ applicationIdUri: "api://orders" }) .withAllowWebApiToBeAuthorizedByACL() .withAppRole("Orders.Read", "Read orders", "Read orders.", { allowedMemberTypes: ["Application"], }) .publishWithAppRoleAssignment(callerIdentity, ["Orders.Read"]);
const api = await builder.addDotnetProject("api", "../Api/Api.csproj");await api.withReference(entraApi);
// Alternatively, pass the app instead of the identity:// await entraApi.publishWithAppRoleAssignment(worker, ["Orders.Read"]);
await builder.build().run();using Aspire.Hosting.Azure;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureContainerAppEnvironment("env");
var callerIdentity = builder.AddAzureUserAssignedIdentity("caller-identity");
var worker = builder.AddDotnetProject("worker", "../Worker/Worker.csproj") .WithAzureUserAssignedIdentity(callerIdentity) // The caller requests a token for the API's application ID URI. .WithEnvironment("ORDERS_API_SCOPE", "api://orders/.default");
var entraApi = builder.AddEntraIdApplication("entra-api") .WithApplicationIdUri("api://orders") .WithAllowWebApiToBeAuthorizedByACL() .WithAppRole(new EntraIdAppRole("Orders.Read", "Read orders", "Read orders.", ["Application"])) .PublishWithAppRoleAssignment(callerIdentity, "Orders.Read");
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(entraApi);
// Alternatively, pass the app instead of the identity:// entraApi.PublishWithAppRoleAssignment(worker, "Orders.Read");
// After adding all resources, run the app...builder.Build().Run();The default application ID URI is api://{clientId}, and the client ID exists only after the deployment creates the registration. This example sets an explicit URI so that the caller’s scope is known before deployment. For other ways to set the URI, see Set the application ID URI.
Configure the caller and the API
Section titled “Configure the caller and the API”Configure the two sides differently.
- Reference the API’s registration from the API app, not from the caller. The registration’s settings identify the API, so the API validates tokens with them.
- Call
WithAllowWebApiToBeAuthorizedByACLon the API’s registration. It stops Microsoft.Identity.Web from requiring arolesorscpclaim in the token, so a token that has no roles reaches your authorization policy instead of being rejected during authentication. - Give the caller the API’s URL and the application ID URI as separate settings. The caller requests a token for the application ID URI followed by
/.default.
In Azure Container Apps, the caller receives its identity’s client ID as AZURE_CLIENT_ID:
using Azure.Core;using Azure.Identity;
var builder = Host.CreateApplicationBuilder(args);
var credential = new ManagedIdentityCredential( ManagedIdentityId.FromUserAssignedClientId(builder.Configuration["AZURE_CLIENT_ID"]!));
AccessToken token = await credential.GetTokenAsync( new TokenRequestContext([builder.Configuration["ORDERS_API_SCOPE"]!]));
// Send token.Token to the API as a bearer token.The API validates the token with Microsoft.Identity.Web and requires the assigned role on protected routes. An identity without the assignment can receive a token, but the token has no roles claim, so the authorization policy rejects the request with a 403 response. Authentication alone doesn’t grant access.
using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>{ options.MapInboundClaims = false; options.TokenValidationParameters.RoleClaimType = "roles";});
builder.Services.AddAuthorization(options => options.AddPolicy("orders", policy => policy.RequireAuthenticatedUser().RequireRole("Orders.Read")));
var app = builder.Build();
app.UseAuthentication();app.UseAuthorization();
app.MapGet("/orders", () => "orders").RequireAuthorization("orders");
app.Run();Grant the deployer the required permissions
Section titled “Grant the deployer the required permissions”Assigning a role is a Microsoft Graph operation that Azure subscription roles such as Owner or Contributor don’t cover. The identity that deploys needs the Microsoft Graph permissions and directory roles listed in Required permissions, and the callers need none of them.
Limitations
Section titled “Limitations”WithAppRole and PublishWithAppRoleAssignment throw for existing registrations. Declare roles and create assignments for those registrations in the Microsoft Entra admin center.