📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show how you would protect an ASP.NET Core API with Microsoft Entra ID. Cover the app registrations, Microsoft.Identity.Web, delegated scopes vs app roles, calling a downstream API on behalf of the user, and letting another Azure service call your API with a managed identity.

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.

Mid-Level Coding Intermediate aspnet-core entra-id managed-identity microsoft-identity-web oauth2 security

🎯 Key points

  • API app registration exposes an App ID URI, delegated scopes and app roles; set requestedAccessTokenVersion = 2 in its manifest so it receives v2 access tokens
  • AddMicrosoftIdentityWebApi validates issuer, audience (client id or App ID URI) and signature
  • Delegated calls: check scp; application calls (client credentials, managed identity): check roles
  • Use oid + tid as the user key
  • On-Behalf-Of (OBO): EnableTokenAcquisitionToCallDownstreamApi + IDownstreamApi, with a distributed token cache
  • Managed identity caller: token for api://<app-id>/.default and an app role assignment to its service principal
  • Credentials: managed identity > federated credentials > certificate in Key Vault > secret with expiry alert
  • Scopes, roles and assignments in Bicep/Terraform with periodic access reviews; 'assignment required' on the API

⏱ 30-second answer

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.

  • A user token carries scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.
  • To call a downstream API as the user, use on-behalf-of: EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.
  • A managed identity caller requests 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, set requestedAccessTokenVersion to 2, and define two kinds of permission. Delegated scopes like Orders.Read are for clients acting for a signed-in user. App roles like Orders.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 AddMicrosoftIdentityWebApi with the AzureAd section: 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 the scp scope for delegated calls or the roles app role for application calls. For users I key data on oid plus tid, never email. If the API calls another API as the user, say Microsoft Graph or our billing API, I use on-behalf-of: EnableTokenAcquisitionToCallDownstreamApi and AddDownstreamApi, 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 for api://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."


Registrations and permissions

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

Token types

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

Production example

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.

🔍 What the interviewer is checking

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

  • Separates API and client registrations, scopes and app roles
  • Checks scp vs roles appropriately
  • Uses OBO correctly with a distributed cache
  • Uses managed identity and app role assignment instead of secrets
  • Uses oid/tid as the key

Red flags

  • Only checks that a token is valid
  • Passes the user's token straight to the downstream API
  • Stores client secrets in config files

📚 Learn in depth

1. What Microsoft.Identity.Web configures

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

2. v1 and v2 access tokens

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.

3. On-behalf-of

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.

4. Managed identity callers

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.

5. Credentials for confidential clients

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.

Try it yourself

  1. Register an API and a client in a dev tenant; get a token with az account get-access-token --scope api://orders/Orders.Read and decode it at jwt.ms.
  2. Call an endpoint that requires roles with a delegated token and confirm a 403.
  3. Enable OBO to call Microsoft Graph /me and watch the token cache hits in logs.
  4. Deploy an Azure Function with a system-assigned managed identity, assign it an app role and call your API.
  5. Flip requestedAccessTokenVersion and compare iss and aud.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Protecting endpoints with only 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.
  • Mistake: Checking 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.
  • Mistake: Using email or UPN as the user key. Why it is wrong: both can change and be reassigned. Instead: oid with tid.
  • Mistake: In-memory token caches with OBO on several instances. Why it is wrong: every instance requests tokens separately, which adds latency and risks Entra throttling. Instead: AddDistributedTokenCaches with Redis or SQL.
  • Mistake: Client secrets in 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.
  • Mistake: Expecting a managed identity's token to contain a role without assigning it. Why it is wrong: app-only tokens only include assigned app roles; there is no consent prompt. Instead: assign the app role to the service principal in infrastructure as code.
  • Mistake: Forwarding the incoming user token to downstream APIs. Why it is wrong: its audience is your API, so the downstream API should reject it, and if it doesn't you have a confused-deputy problem. Instead: on-behalf-of for a new token with the right audience.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions client credentials or on-behalf-of Why: Checks understanding of the underlying OAuth flows
    How to answer

    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.

    • Authorisation code + PKCE: the browser gets a one-time code, and the client swaps it for tokens, proving with a code_verifier that it started the flow. Use it for web apps, SPAs and mobile.
    • Client credentials: a service authenticates as itself; no user.
    • Implicit and password flows are deprecated (RFC 9700); OAuth 2.1, still an IETF draft in late 2026, makes that official.

    The trade-off: the redirect-based flows are more moving parts, but credentials never touch your app.

  2. When: Candidate mentions certificates or secrets in Key Vault Why: Checks how they manage configuration and secrets with managed identity
    How to answer

    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.

  3. When: Candidate mentions roles and scp claims Why: Checks claim mapping and where permissions come from
    How to answer

    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.

🛠 Real-world problems: how you handle them

Any app in the tenant could call the orders API
Situation
An internal [orders] API on Azure App Service (Australia East), used by [4] client apps, validated Entra ID tokens but only required an authenticated user. It held [customer order and address] data.
Signals
A pen test report showed that a newly created test app registration with no granted permissions obtained a token and read [orders]; Application Insights showed calls from [two] unknown client ids (`azp`/`appid` claims).
Investigation
Decoded the test token in jwt.ms and confirmed `aud` was the API with no `scp` or `roles`; listed client ids calling the API from logs grouped by `azp`; reviewed the API's enterprise application: 'Assignment required' was off; checked which endpoints each legitimate client actually used.
Resolution
Same week: enabled 'Assignment required' on the API's enterprise application and added explicit app role assignments for the [4] known clients. Then added per-endpoint policies on `scp` and `roles`, moved [3] service callers to managed identities, and blocked unknown `azp` values in a temporary middleware until the policies shipped.
Prevention
App registrations, scopes, roles and assignments defined in Bicep and reviewed in pull requests; an integration test that calls each endpoint with a token lacking the scope and expects 403; a dashboard of calls by client id with an alert on new ones.

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.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me