Securing an ASP.NET Core API with Microsoft Entra ID: app registrations, Microsoft.Identity.Web, scp vs roles, on-behalf-of with IDownstreamApi, token caches, and managed identity callers.
Register the API in Entra ID with an App ID URI, delegated scopes (Orders.Read) for user calls and app roles (Orders.Read.All) for application calls. Register each client separately and grant it those permissions. In the API, AddMicrosoftIdentityWebApi (Microsoft.Identity.Web) wires up JWT bearer validation against your tenant.
scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.api://<app-id>/.default; you assign it an app role.The trade-off: Entra does the heavy lifting, but permissions and consent live in the portal, so manage them as code.
"There are always at least two app registrations: one for the API and one per client. On the API registration I set the App ID URI,
api://orders, setrequestedAccessTokenVersionto 2, and define two kinds of permission. Delegated scopes likeOrders.Readare for clients acting for a signed-in user. App roles likeOrders.Read.All, with allowed member type 'Applications', are for daemons and services with no user. Each client registration requests the permissions it needs and an admin grants consent.In the API I call
AddMicrosoftIdentityWebApiwith theAzureAdsection: instance, tenant id and client id. It configures JWT bearer validation for that tenant, accepts both the client id and App ID URI as audience, and handles signing-key refresh. Then authorisation: a valid token isn't enough, any app in the tenant can get one, so each endpoint requires either thescpscope for delegated calls or therolesapp role for application calls. For users I key data onoidplustid, never email. If the API calls another API as the user, say Microsoft Graph or our billing API, I use on-behalf-of:EnableTokenAcquisitionToCallDownstreamApiandAddDownstreamApi, and a distributed token cache because we run several instances. When another Azure service calls us, I don't give it a secret: its managed identity requests a token forapi://orders/.default, and I assign it the app role on our API's service principal.The mistake I see is APIs that only call
RequireAuthorization(), so any app registration in the tenant can call them, and client secrets that expire on a Friday. The senior line: the token proves who issued it and for whom; scopes and roles say what it may do, and you must check them."
| Thing | Where | Example |
|---|---|---|
| App ID URI | API registration > Expose an API | api://orders |
| Delegated scope | API registration > Expose an API | Orders.Read -> scp claim |
| App role (applications) | API registration > App roles | Orders.Read.All -> roles claim |
| App role (users/groups) | API registration > App roles | Orders.Approver -> roles claim |
| Client permissions | Client registration > API permissions | Delegated or application, admin consent |
| Managed identity access | Enterprise app (service principal) | App role assignment via Graph or CLI |
| Caller | Flow | Claims to check |
|---|---|---|
| SPA / web app with a user | Code + PKCE | scp, plus user roles if used |
| Your API calling another as the user | On-behalf-of | scp at the downstream API |
| Daemon / background job | Client credentials | roles |
| Azure Function or App Service | Managed identity | roles |
At [company] an internal API only required an authenticated token; a pen test showed [an unrelated test app] in the same tenant could read [order data]. Adding scope and app-role policies per endpoint, and switching [3] service callers from secrets to managed identities, closed the finding and removed [all] secret-expiry incidents for those services.
Checks practical experience securing APIs with Entra ID beyond the template: permissions design, the difference between user and app tokens, and credential hygiene.
Green flags
scp vs roles appropriatelyoid/tid as the keyRed flags
AddMicrosoftIdentityWebApi("AzureAd")
-> AddJwtBearer with Authority = {Instance}{TenantId}/v2.0
-> audience: ClientId and api://ClientId (or the configured Audience)
-> issuer validation for the tenant (multi-tenant: AadIssuerValidator)
-> signing keys from the tenant's JWKS, refreshed on rollover
EnableTokenAcquisitionToCallDownstreamApi()
-> MSAL confidential client (secret, certificate or federated credential)
-> ITokenAcquisition / IDownstreamApi with token caches
The token version depends on the API's registration (requestedAccessTokenVersion), not on the endpoint the client used. v1 tokens have issuer https://sts.windows.net/{tid}/ and often the App ID URI as audience; v2 tokens have issuer https://login.microsoftonline.com/{tid}/v2.0 and the client id as audience. Mismatches between the expected and actual version are a classic cause of 401s.
SPA --AT(aud=orders, scp=Orders.Read)--> Orders API
Orders API --POST /token grant_type=jwt-bearer, assertion=AT, scope=api://billing/Billing.Read--> Entra ID
Entra ID --AT(aud=billing, same user)--> Orders API --> Billing API
The downstream token keeps the user's identity, so the downstream API can apply the user's permissions. The cache key includes the incoming token, so a distributed cache (Redis or SQL) avoids a token request per call on every instance.
A managed identity is a service principal without a credential you manage. The caller uses DefaultAzureCredential or ManagedIdentityCredential to request api://orders/.default. Because it is app-only, Entra only includes app roles that have been assigned to that service principal, which you do with Microsoft Graph (New-MgServicePrincipalAppRoleAssignment) or Bicep/Terraform. There is no consent screen.
Prefer, in order: managed identity (Azure-hosted), workload identity federation (GitHub Actions, Kubernetes, other clouds), certificates in Key Vault, and only then client secrets with expiry alerts.
az account get-access-token --scope api://orders/Orders.Read and decode it at jwt.ms.roles with a delegated token and confirm a 403./me and watch the token cache hits in logs.requestedAccessTokenVersion and compare iss and aud.An API protected by Entra ID, with separate policies for delegated and application callers, plus an on-behalf-of call.
// appsettings.json (no secrets: the client credential comes from a certificate or federated identity)
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<tenant-guid>",
"ClientId": "<orders-api-client-id>",
"Audience": "api://orders"
},
"Billing": { "BaseUrl": "https://billing.internal.example.com.au/", "Scopes": [ "api://billing/Billing.Read" ] }
}
// Program.cs (.NET 10) - packages: Microsoft.Identity.Web, Microsoft.Identity.Web.DownstreamApi
using System.Security.Claims;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication()
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddDownstreamApi("Billing", builder.Configuration.GetSection("Billing"))
.AddDistributedTokenCaches(); // shared across instances
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration["Redis"]);
builder.Services.AddAuthorizationBuilder()
// A user calling through a client app: delegated scope in 'scp'.
.AddPolicy("orders.read.user", p => p.RequireAssertion(ctx =>
ctx.User.FindFirstValue("http://schemas.microsoft.com/identity/claims/scope")?.Split(' ').Contains("Orders.Read") == true
|| ctx.User.FindFirstValue("scp")?.Split(' ').Contains("Orders.Read") == true))
// A daemon or managed identity: app role in 'roles'.
.AddPolicy("orders.read.app", p => p.RequireRole("Orders.Read.All"));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/orders/mine", async (ClaimsPrincipal user, IDownstreamApi downstream, CancellationToken ct) =>
{
var userKey = $"{user.GetTenantId()}:{user.GetObjectId()}"; // oid + tid, not email
// On-behalf-of: exchanges the caller's token for one scoped to the billing API.
var invoices = await downstream.GetForUserAsync<List<InvoiceDto>>("Billing",
o => o.RelativePath = $"invoices?user={Uri.EscapeDataString(userKey)}", cancellationToken: ct);
return Results.Ok(new { userKey, invoices });
}).RequireAuthorization("orders.read.user");
app.MapGet("/orders/export", () => Results.Ok()).RequireAuthorization("orders.read.app");
app.Run();
public sealed record InvoiceDto(string Id, decimal Amount);
// The caller: an Azure Function using its managed identity (no secret anywhere).
using Azure.Core;
using Azure.Identity;
var credential = new DefaultAzureCredential();
AccessToken token = await credential.GetTokenAsync(new TokenRequestContext(["api://orders/.default"]), ct);
httpClient.DefaultRequestHeaders.Authorization = new("Bearer", token.Token);
RequireAuthorization(). Why it is wrong: any app registration in the tenant can obtain a token for your API's audience in some configurations, and every client gets every endpoint. Instead: require specific scopes or app roles per endpoint.scp for daemon callers. Why it is wrong: app-only tokens have no scp; they carry roles. Instead: separate policies, or RequiredScopeOrAppPermission from Microsoft.Identity.Web.oid with tid.AddDistributedTokenCaches with Redis or SQL.appsettings.json. Why it is wrong: they leak through source control and expire, causing outages. Instead: managed identity, federated credentials or certificates from Key Vault.Entra ID removes token validation as a problem and replaces it with permission management. The senior work is designing scopes and app roles that match real access patterns, keeping them in Bicep or Terraform so they are reviewed, and getting rid of client secrets. I also check how many apps can call an API: the list should be explicit, ideally with 'assignment required' on the API's enterprise application.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Delegated scopes | Clients acting for a user | Consent and scope design | Background jobs |
| App roles for applications | Daemons, managed identities, partners | Role assignment process | When user context matters |
| On-behalf-of | API chains that must keep the user's identity | Extra token request (cached), more consent | When the downstream only needs service identity (use app-only) |
| Managed identity | Azure-hosted callers | Role assignments in IaC | Callers outside Azure (use federated credentials) |
Measure: 401/403 rates per client id, token acquisition latency and cache hit rate for OBO, and secret or certificate expiry dates.
OAuth 2.0 is a framework for delegated authorisation: a client gets an access token to call an API on a user's (or its own) behalf. It says nothing about who the user is. OpenID Connect is a thin identity layer on top that adds the ID token (a JWT about the user, for the client), the userinfo endpoint and discovery metadata.
code_verifier that it started the flow. Use it for web apps, SPAs and mobile.The trade-off: the redirect-based flows are more moving parts, but credentials never touch your app.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
A claim is a type/value statement about the user made by an issuer, such as sub=42 or roles=Admin. A ClaimsPrincipal holds one or more ClaimsIdentity objects; each identity's NameClaimType and RoleClaimType decide what User.Identity.Name and User.IsInRole read, so a role is just a claim.
The JWT and OIDC handlers map inbound claims by default (sub becomes ClaimTypes.NameIdentifier); MapInboundClaims = false keeps the issuer's names. IClaimsTransformation can add application claims after authentication, but it runs on every authenticate call, so it must be idempotent and cached.
Permissions: take identity and coarse roles from the identity provider, and fine-grained, app-specific permissions from your own store. The trade-off is token size and staleness versus a lookup per request.
How to tell it (STAR)
**S:** A pen test found that any app registration in our tenant could read data from our [orders] API, because it only checked for a valid token. **T:** I owned the fix across the API and its [4] clients. **A:** I turned on assignment-required and assigned app roles to the known clients as an immediate block, then added scope and app-role policies per endpoint, moved our service callers to managed identities, and put all registrations into Bicep. **R:** The re-test passed, unknown client calls dropped to [zero], and we retired [3] client secrets that had caused [two] expiry outages that year.
Last updated 23 Nov 2026.