Aspirerelease/17.0
Watch Aspire live streamsDokumentationPrøv Aspire

Application roles with Entra ID

Dette indhold er ikke tilgængeligt i dit sprog endnu.

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.

Use WithAppRole to declare a role on a registration that Aspire creates. Declaring a role doesn’t assign it to anyone.

apphost.mts
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();

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.

SettingDescription
valueThe value in the roles claim, such as Admin. It must be unique for the application.
displayNameThe name that the Microsoft Entra admin center shows.
descriptionThe text that assignment and consent experiences show.
allowedMemberTypesPassed through to Microsoft Graph, such as User or Application. Include Application to let managed identities hold the role. The default is User.
idOptional. When omitted, the ID is derived from the resource name and role value, so changing either creates a different role.
isEnabledWhether 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.

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 in two steps.

  1. Remove the PublishWithAppRoleAssignment calls for the role, set isEnabled to false, and leave the role declared. Deploy.
  2. 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.

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.

apphost.mts
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();

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 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 WithAllowWebApiToBeAuthorizedByACL on the API’s registration. It stops Microsoft.Identity.Web from requiring a roles or scp claim 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:

Worker/Program.cs
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.

Api/Program.cs
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.

WithAppRole and PublishWithAppRoleAssignment throw for existing registrations. Declare roles and create assignments for those registrations in the Microsoft Entra admin center.