# 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](/integrations/security/microsoft-entra-id/).

## Prerequisites

- An AppHost with the [📦 Aspire.Hosting.Azure.EntraId](https://www.nuget.org/packages/Aspire.Hosting.Azure.EntraId) package. For the other prerequisites, see [Microsoft Entra ID integration](/integrations/security/microsoft-entra-id/#prerequisites).
- The [📦 Aspire.Hosting.Azure.AppContainers](https://www.nuget.org/packages/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](/integrations/frameworks/dotnet/dotnet-host/).
- [Service defaults](/get-started/csharp-service-defaults/) in both projects. Their `MapDefaultEndpoints` method maps the `/health` endpoint that the AppHost probes.
- The [📦 Microsoft.Identity.Web](https://www.nuget.org/packages/Microsoft.Identity.Web) package in the web and API projects, to sign in users and validate tokens. The app code uses its `Microsoft.Identity.Web` and `Microsoft.Identity.Web.Resource` namespaces.
- [Local Azure provisioning](/integrations/cloud/azure/local-provisioning/) configured with your subscription and location.

## 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.

```typescript title="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();
```

```csharp title="AppHost.cs"
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:

- `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](/integrations/security/microsoft-entra-id/expose-and-call-apis/#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](/integrations/security/microsoft-entra-id/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](/integrations/security/microsoft-entra-id/redirect-uris-and-sign-in/).

## 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.

```csharp title="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]`:

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

## 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.

```csharp title="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](https://www.nuget.org/packages/Microsoft.Identity.Web.DownstreamApi) package. For the sign-in pages and authorization of your app model, follow the [Microsoft.Identity.Web documentation](https://learn.microsoft.com/entra/msal/dotnet/microsoft-identity-web/).

## Run the scenario locally

1. Start the AppHost with `aspire run`.
1. 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](/integrations/security/microsoft-entra-id/lifecycle-and-permissions/#separate-registrations-with-a-tenant-scoped-suffix).
1. 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.
1. Open the `webfrontend` endpoint and sign in. If nobody consented to `access_as_user` yet, Entra ID asks you to consent to it.
1. 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](/integrations/security/microsoft-entra-id/client-credentials/#local-developer-certificate).

If `webfrontend-entra` reports `Missing subscription configuration`, Azure provisioning isn't configured. See [Lifecycle and permissions](/integrations/security/microsoft-entra-id/lifecycle-and-permissions/#troubleshoot-entra-id-errors).

## Deploy to Azure Container Apps

Run `aspire deploy` from the AppHost directory. For more information about deployment, see [Deploy with Aspire](/deployment/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:

| 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](/integrations/security/microsoft-entra-id/lifecycle-and-permissions/#required-permissions) describes. Deleting the resource group doesn't delete the registrations, so [clean them up separately](/integrations/security/microsoft-entra-id/lifecycle-and-permissions/#clean-up-registrations).

## See also

- [Microsoft Entra ID integration](/integrations/security/microsoft-entra-id/)
- [Expose and call APIs](/integrations/security/microsoft-entra-id/expose-and-call-apis/)
- [Client credentials](/integrations/security/microsoft-entra-id/client-credentials/)
- [Lifecycle and permissions](/integrations/security/microsoft-entra-id/lifecycle-and-permissions/)
- [Web app that signs in users](https://learn.microsoft.com/entra/identity-platform/scenario-web-app-sign-user-overview)
- [Protected web API](https://learn.microsoft.com/entra/identity-platform/scenario-protected-web-api-overview)