You shipped the SPA. You shipped the API. Bedrock extraction runs. Aurora holds metadata. OpenSearch answers semantic queries. Then someone says: “Production needs Microsoft Entra login.” Fine. You register an app. You add Microsoft.Identity.Web. You deploy to Fargate behind CloudFront.
The login button sends you to Microsoft. Microsoft sends you back. And then—nothing. Or worse, a loop. Or a 404 on /signin-oidc that nginx serves with a cheerful React shell.
Entra ID AWS application integration is not “drop in OIDC middleware.” It is identity plus edge routing plus outbound networking plus a BFF contract your frontend did not have in dev. This post is what we learned wiring Entra into a document-management platform on AWS—genericized, no customer names, scars included.

Not this post: federating Azure DevOps into AWS for deploys. That is pipeline OIDC (IAM roles, AssumeRoleWithWebIdentity). See AWS OIDC Azure DevOps. Here we mean humans signing into the app.
In Brief
- Use the BFF pattern: Entra authorization code flow on the API; session cookie to the browser; no access tokens in
localStorage. - Set
ExternalUrlwhen CloudFront (or a custom domain) is the public host—redirect_urimust not point at the internal ALB hostname. - Route
/auth/*,/signin-oidc,/signout-oidcto the API service on the ALB—not the static client target group. - Enable NAT (or equivalent egress) so Fargate can reach
login.microsoftonline.comfor metadata and token exchange. - Keep Mock JWT and a secondary Bearer scheme for local dev and import scripts; register routes conditionally so endpoints do not collide.
The Platform Shape (Why Auth Hurts Here)
Picture a research document system:
- React SPA for search, validation queues, uploads.
- .NET WebApi BFF in front of a gRPC backend.
- PDFs in S3 → GuardDuty → Step Functions → Amazon Bedrock extraction → PostgreSQL + OpenSearch Serverless.
- Deployed on ECS Fargate in private subnets, public entry via ALB and CloudFront.
In sandbox you mocked login: pick a role, get a JWT, store it, call /api/* with Authorization: Bearer. Fast. Convenient. Completely unlike production Entra.
Production wants OpenID Connect with app roles from the tenant directory. The browser should never hold a Microsoft access token. The server exchanges the code, validates the ID token, and issues an HttpOnly cookie. That is the Entra ID BFF pattern—and it changes routing, config, and how your React router decides “am I logged in?”
Target Architecture (ASCII)
Browser Edge AWS VPC (private)
─────── ──── ─────────────────
GET /studies ──► CloudFront ──► ALB listener
│
┌─────────────────┼─────────────────┐
│ │ │
/api/* /auth/* /signin-oidc /* (SPA)
│ /signout-oidc │
▼ ▼ ▼
WebApi BFF WebApi BFF nginx + static
(Fargate) (Fargate) (Fargate)
│ │
│ HTTPS outbound │ (NAT Gateway)
└────────┬────────┘
▼
login.microsoftonline.com
(authorize + token endpoints)
Three ideas in one diagram:
- OIDC callbacks hit the API, not the SPA container.
- Egress from private tasks to Microsoft is mandatory.
- CloudFront is what Entra must see in redirect URIs—not the ALB DNS name.
The Happy Path (Authorization Code + Cookie)
- User opens the app → SPA calls
/api/auth/me→ 401. - SPA sets
window.location = '/auth/login'(full page navigation—not client-side routing). - API issues OIDC challenge → redirect to Microsoft.
- User signs in; Microsoft redirects to
https://{public-host}/signin-oidc?code=.... - API exchanges code server-side, validates token, maps
rolesclaims to role principals. - API sets encrypted session cookie (
HttpOnly,Secure,SameSite=Lax). - Redirect to
/; subsequent/api/*calls authenticate via cookie.
Logout: GET /auth/logout clears the cookie and hits Entra sign-out.
Microsoft documents the web app flow in Microsoft identity platform and OpenID Connect. For ASP.NET Core, Microsoft.Identity.Web is the practical default.
Configuration That Actually Matters
| Setting | Where | Why |
|---|---|---|
Auth:Provider |
EntraId vs Mock |
One switch for entire stack behavior |
Auth:EntraId:TenantId / ClientId |
CDK → ECS env | Issuer and audience validation |
Auth:EntraId:ClientSecret |
Secrets Manager → ECS secret | Never in git or plain env files |
Auth:EntraId:ExternalUrl |
CloudFront or custom domain | Overrides redirect_uri on challenge |
CallbackPath |
/signin-oidc |
Must match Entra app registration exactly |
enableNatGateway |
CDK L1 when Entra on | Outbound HTTPS to Microsoft |
The ExternalUrl override is the one line that saves you from AADSTS50011:
options.Events.OnRedirectToIdentityProvider = context =>
{
if (!string.IsNullOrEmpty(externalUrl))
context.ProtocolMessage.RedirectUri =
$"{externalUrl.TrimEnd('/')}{options.CallbackPath}";
return Task.CompletedTask;
};
Without it, the middleware may build redirect_uri from the internal host the container sees—fine behind a single hostname in dev, fatal behind CloudFront.
Issues We Hit (And Fixes)

| Symptom | Likely cause | Fix |
|---|---|---|
AADSTS50011 redirect URI mismatch |
Entra registered https://d123.cloudfront.net/signin-oidc but challenge used ALB host |
ExternalUrl + re-register URI in Entra |
404 on /signin-oidc with SPA HTML |
ALB default action sends all paths to client TG | Listener rules: OIDC paths → API target group |
AmbiguousMatchException on /api/auth/me |
Mock and Entra route tables both registered | Register one mode in Program.cs |
| Login loop / instant 401 after success | Cookie Secure on HTTP, or wrong site |
HTTPS end-to-end; SameSite=Lax for top-level redirects |
| API task healthy but auth middleware fails at startup | No route to login.microsoftonline.com |
NAT on private subnets (enableNatGateway) |
| User lands in app with no role | Entra sends roles array; policies expect role |
OnTokenValidated: explode array into role claims |
| Import scripts fail after Entra cutover | Scripts used mock POST /api/auth/login |
Keep mock login or secondary JWT Bearer scheme for automation |
SPA still navigates to /login |
Router not BFF-aware | If no localStorage token → redirect /auth/login |
Most of these are infrastructure or routing bugs wearing an auth costume. You will grep JWT code for hours before noticing the ALB sent /signin-oidc to nginx.
ALB Rules (Concrete)
When API and SPA share one hostname, path-based routing is non-negotiable:
Priority 10: /api/* → api-target-group
Priority 20: /auth/* → api-target-group
Priority 21: /signin-oidc → api-target-group
Priority 22: /signout-oidc → api-target-group
Priority 23: /scalar/* → api-target-group (optional: OpenAPI UI)
Default: /* → client-target-group
Miss one OIDC path and Microsoft’s redirect lands in the wrong container. The failure mode looks like “Entra is broken.” It is not. Your listener is.
AWS documents listener rules in Listener rules for your Application Load Balancer.
Dual Mode: Mock vs Entra (Best Practice)
Do not fork the codebase per environment. Use one Auth:Provider flag:
| Mode | Default scheme | Frontend signal | Good for |
|---|---|---|---|
Mock |
JWT Bearer | Token in localStorage |
Local dev, fast UI work |
EntraId |
Cookie + OIDC challenge | No token; cookie session | Production SSO |
Downstream authorization stays identical: same policy names (Admin, Researcher, …), same role strings (admin, grm, …). Only the front door changes.
Best practice: keep a secondary JWT Bearer handler in Entra mode for batch importers and integration tests—humans use cookies, machines use scoped secrets. Document which endpoints accept which scheme. Do not disable mock login in Entra mode if operations still depend on scripted imports; gate it with config instead.
Infrastructure Checklist (CDK / ECS)
- Secrets Manager secret for client secret; execution role can read it.
-
enableNatGateway: truewhenauthProvider: EntraId(token exchange + OIDC metadata). - Task env:
Auth__EntraId__*double-underscore mapping for .NET config. -
externalUrlin environment config matches public URL users type in the browser. - CloudFront → ALB origin; forward cookies on
/apiand auth paths. - Document that stack recreate may change CloudFront domain → Entra redirect URI must be updated (Part 2 of this series).
Security Posture (Short)
- Authorization code flow only—not implicit. Tokens stay server-side.
- Cookie: HttpOnly, Secure, SameSite=Lax.
- Client secret only in Secrets Manager; rotate on customer IT schedule.
- App roles in Entra—not group overloading unless you have a clear mapping story.
- Least privilege on ECS task role unrelated to Entra; user identity rides the cookie into the BFF, then gRPC metadata to backend.
For AWS-hosted apps, also review Security best practices for Amazon ECS—auth is one layer; task IAM and secrets handling are the rest.
What We Would Do Differently
- Draw the ALB rule table before writing OIDC middleware. Saves a day.
- Set
ExternalUrlin the first deploy, not after the firstAADSTS50011screenshot. - Give customer IT a redirect URI checklist with exact paths (
/signin-oidc,/signout-oidc) before they register the app. - Plan NAT cost when enabling Entra in a sandbox VPC that previously had no egress.
- Teach the frontend one rule: BFF mode never uses
/loginas the primary gate.
Series Next
This is part 1 of Entra ID on AWS (user SSO):
| Part | Topic |
|---|---|
| 2 | App registration, app roles, redirect URI lifecycle when CloudFront changes |
| 3 | Dual auth for scripts, claim propagation, testing matrix |
Pipeline federation (ADO → AWS) stays in the Hybrid CI/CD series. Same acronym family. Different threat model.
Related: Azure DevOps AWS integration · Document pipeline event-driven deploy
If you have war stories from Entra behind CloudFront—or you routed OIDC through API Gateway instead of ALB—I would like to hear them.