Aspirerelease/17.0
Watch Aspire live streamsDokumentasiCoba Aspire

Secure a web app and API with Entra ID

Konten ini belum tersedia dalam bahasa Anda.

This walkthrough models a common scenario in one AppHost. An API exposes a delegated scope, and a web app signs users in with Microsoft Entra ID and calls the API on their behalf. You run it locally, and then deploy it to Azure Container Apps. The web app authenticates to Entra ID with a developer certificate locally and with a managed identity in Azure, so no client secret is involved.

Aspire creates the two registrations and passes their settings to your apps. For the integration overview, see Microsoft Entra ID integration.

The API registration exposes the access_as_user scope. The web registration declares that it needs that scope, trusts a certificate when you run locally, and trusts the managed identity of its container app when you deploy.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment("env");
const apiEntra = await builder.addEntraIdApplication("apiservice-entra")
.withScope("access_as_user", "Access the weather API on behalf of the signed-in user");
const apiService = await builder.addDotnetProject("apiservice", "../ApiService/ApiService.csproj")
.withReference(apiEntra)
.withHttpHealthCheck({ path: "/health" });
const webEntra = await builder.addEntraIdApplication("webfrontend-entra")
.withApiPermissions(apiEntra, ["access_as_user"])
.runWithLocalDeveloperCertificateCredential()
.publishWithFederatedManagedIdentityCredential();
const webFrontend = await builder.addDotnetProject("webfrontend", "../Web/Web.csproj")
.withExternalHttpEndpoints()
.withHttpHealthCheck({ path: "/health" })
.withReference(webEntra)
.withReference(apiService)
.waitFor(apiService);
await webEntra.withRedirectUris(await webFrontend.getEndpoint("https"), {
callbackPaths: ["/signin-oidc", "/signout-callback-oidc"],
});
await builder.build().run();

The AppHost does the following:

  • WithScope exposes the access_as_user delegated scope and gives the API registration the default api://{clientId} application ID URI.
  • WithApiPermissions lists the scope in the web registration’s API permissions. It doesn’t grant consent. For a version that does, see Declare permissions and consent.
  • RunWithLocalDeveloperCertificateCredential gives the web app a short-lived certificate credential when you run locally. PublishWithFederatedManagedIdentityCredential replaces it with a federated credential for the container app’s managed identity when you deploy. For more information, see Client credentials.
  • WithReference(webEntra) gives the web app its registration settings and the DownstreamApis entry for the API. WithReference(apiService) lets the web app reach the API through service discovery.
  • WithRedirectUris derives the sign-in and sign-out callbacks from the web app’s HTTPS endpoint, so you don’t hard-code a port or host name. The callback paths must match the paths that the web app uses. For more information, see Redirect URIs and sign-in.

The API validates bearer tokens that Microsoft Entra ID issued for its registration. Referencing the API registration sets AzureAd__Instance, AzureAd__TenantId, AzureAd__ClientId, and AzureAd__Scopes. The AzureAd section is where Microsoft.Identity.Web looks for its settings.

ApiService/Program.cs
builder.AddServiceDefaults();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapDefaultEndpoints();
app.Run();

AzureAd__Scopes holds the space-separated names of the API’s enabled scopes. The [RequiredScope] attribute doesn’t read that setting unless you name it, and it enforces nothing without [Authorize]:

ApiService/Controllers/WeatherForecastController.cs
[ApiController]
[Route("weatherforecast")]
[Authorize]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
public class WeatherForecastController : ControllerBase
{
// ...
}

The web app signs users in with OpenID Connect and acquires a token for the API on behalf of the signed-in user. Referencing the web registration sets the AzureAd__* settings and a DownstreamApis__apiservice__Scopes__0 entry with the value api://{apiClientId}/access_as_user. The entry is named apiservice because that resource references the API registration.

Web/Program.cs
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
builder.Services.AddHttpClient<WeatherApiClient>(client => client.BaseAddress = new("https+http://apiservice"))
.AddMicrosoftIdentityMessageHandler(
builder.Configuration.GetSection("DownstreamApis:apiservice"), "DownstreamApis:apiservice");

WeatherApiClient is your own typed HttpClient class. The DownstreamApis entry holds scopes, not the API’s address, so the code sets the base address with service discovery. The message handler acquires a token for the entry’s scopes and adds it to each request. To call APIs through IDownstreamApi instead, call AddDownstreamApis(builder.Configuration.GetSection("DownstreamApis")) from the 📦 Microsoft.Identity.Web.DownstreamApi package. For the sign-in pages and authorization of your app model, follow the Microsoft.Identity.Web documentation.

  1. Start the AppHost with aspire run.
  2. When the dashboard prompts for Azure provisioning settings, select the subscription, resource group, and location. You can also set an optional Tenant-scoped resource suffix so that your registrations don’t collide with a teammate’s. For more information, see Separate registrations with a tenant-scoped suffix.
  3. Wait for apiservice-entra and webfrontend-entra to reach the Running state. Aspire creates both registrations and their service principals the first time. The resources show links to the app registration in the Azure portal.
  4. Open the webfrontend endpoint and sign in. If nobody consented to access_as_user yet, Entra ID asks you to consent to it.
  5. Use a page of the web app that calls the API. The web app redeems the authorization code with the developer certificate and calls the API with a token for api://{apiClientId}/access_as_user.

Locally, the web app receives the developer certificate as a base64-encoded credential in AzureAd__ClientCredentials. Use it for development only, as described in Local developer certificate.

If webfrontend-entra reports Missing subscription configuration, Azure provisioning isn’t configured. See Lifecycle and permissions.

Run aspire deploy from the AppHost directory. For more information about deployment, see Deploy with Aspire.

When you deploy:

  • Aspire creates or updates both registrations and a user-assigned managed identity for the web container app.
  • PublishWithFederatedManagedIdentityCredential adds a federated credential to the web registration that trusts the web container app’s managed identity.
  • WithRedirectUris registers https://{web-fqdn}/signin-oidc and https://{web-fqdn}/signout-callback-oidc for the container app’s fully qualified domain name.
  • The RunWithLocalDeveloperCertificateCredential call does nothing, because it applies only when you run locally.

Each container app receives these settings:

AppSettings
webfrontendAzureAd__Instance, AzureAd__TenantId, and AzureAd__ClientId
webfrontendAzureAd__ClientCredentials__0__SourceType set to SignedAssertionFromManagedIdentity, and AzureAd__ClientCredentials__0__ManagedIdentityClientId
webfrontendDownstreamApis__apiservice__Scopes__0 set to api://{apiClientId}/access_as_user
apiserviceAzureAd__Instance, AzureAd__TenantId, and AzureAd__ClientId
apiserviceAzureAd__Scopes set to access_as_user

After the deployment, open the web app’s address and sign in. Entra ID asks for consent unless you or an administrator already consented. Then use a page that calls the API.

The deploying identity needs the permissions that Lifecycle and permissions describes. Deleting the resource group doesn’t delete the registrations, so clean them up separately.