Secure a web app and API with Entra ID
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.
Prerequisites
Section titled “Prerequisites”- An AppHost with the 📦 Aspire.Hosting.Azure.EntraId package. For the other prerequisites, see Microsoft Entra ID integration.
- The 📦 Aspire.Hosting.Azure.AppContainers package, for the Azure Container Apps environment.
- A web project and an API project that use .NET. The AppHost adds them with
AddDotnetProject, which comes from the Dotnet hosting integration. - Service defaults in both projects. Their
MapDefaultEndpointsmethod maps the/healthendpoint that the AppHost probes. - The 📦 Microsoft.Identity.Web package in the web and API projects, to sign in users and validate tokens. The app code uses its
Microsoft.Identity.WebandMicrosoft.Identity.Web.Resourcenamespaces. - Local Azure provisioning configured with your subscription and location.
Model the AppHost
Section titled “Model the AppHost”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.
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();var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureContainerAppEnvironment("env");
var apiEntra = builder.AddEntraIdApplication("apiservice-entra") .WithScope("access_as_user", "Access the weather API on behalf of the signed-in user");
var apiService = builder.AddDotnetProject("apiservice", "../ApiService/ApiService.csproj") .WithReference(apiEntra) .WithHttpHealthCheck("/health");
var webEntra = builder.AddEntraIdApplication("webfrontend-entra") .WithApiPermissions(apiEntra, "access_as_user") .RunWithLocalDeveloperCertificateCredential() .PublishWithFederatedManagedIdentityCredential();
var webFrontend = builder.AddDotnetProject("webfrontend", "../Web/Web.csproj") .WithExternalHttpEndpoints() .WithHttpHealthCheck("/health") .WithReference(webEntra) .WithReference(apiService) .WaitFor(apiService);
webEntra.WithRedirectUris(webFrontend.GetEndpoint("https"), "/signin-oidc", "/signout-callback-oidc");
// After adding all resources, run the app...builder.Build().Run();The AppHost does the following:
WithScopeexposes theaccess_as_userdelegated scope and gives the API registration the defaultapi://{clientId}application ID URI.WithApiPermissionslists the scope in the web registration’s API permissions. It doesn’t grant consent. For a version that does, see Declare permissions and consent.RunWithLocalDeveloperCertificateCredentialgives the web app a short-lived certificate credential when you run locally.PublishWithFederatedManagedIdentityCredentialreplaces 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 theDownstreamApisentry for the API.WithReference(apiService)lets the web app reach the API through service discovery.WithRedirectUrisderives 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.
Protect the API
Section titled “Protect the API”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.
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]:
[ApiController][Route("weatherforecast")][Authorize][RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]public class WeatherForecastController : ControllerBase{ // ...}Sign in users and call the API
Section titled “Sign in users and call the API”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.
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.
Run the scenario locally
Section titled “Run the scenario locally”- Start the AppHost with
aspire run. - 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.
- Wait for
apiservice-entraandwebfrontend-entrato 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. - Open the
webfrontendendpoint and sign in. If nobody consented toaccess_as_useryet, Entra ID asks you to consent to it. - 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.
Deploy to Azure Container Apps
Section titled “Deploy to Azure Container Apps”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.
PublishWithFederatedManagedIdentityCredentialadds a federated credential to the web registration that trusts the web container app’s managed identity.WithRedirectUrisregistershttps://{web-fqdn}/signin-oidcandhttps://{web-fqdn}/signout-callback-oidcfor the container app’s fully qualified domain name.- The
RunWithLocalDeveloperCertificateCredentialcall does nothing, because it applies only when you run locally.
Each container app receives these settings:
| App | Settings |
|---|---|
webfrontend | AzureAd__Instance, AzureAd__TenantId, and AzureAd__ClientId |
webfrontend | AzureAd__ClientCredentials__0__SourceType set to SignedAssertionFromManagedIdentity, and AzureAd__ClientCredentials__0__ManagedIdentityClientId |
webfrontend | DownstreamApis__apiservice__Scopes__0 set to api://{apiClientId}/access_as_user |
apiservice | AzureAd__Instance, AzureAd__TenantId, and AzureAd__ClientId |
apiservice | AzureAd__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.