惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
月光博客
月光博客
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
IT之家
IT之家
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
S
SegmentFault 最新的问题
宝玉的分享
宝玉的分享
博客园 - Franky
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
博客园 - 司徒正美
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Beyond Localhost: Implementing Production-Grade Entra ID ...
Mo · 2026-05-11 · via DEV Community

We’ve all been there. You spend two days wiring up authentication for a distributed project. It works perfectly on your machine with a mock provider or a local database, but the moment you try to integrate a real enterprise identity provider like Microsoft Entra ID, the wheels come off. Redirect URIs don't match, audience validation fails, and your local environment feels nothing like the production environment you're supposed to be targeting.

When I started building out my latest CleanArchitecture template, I wanted to solve this once and for all. I wanted an architecture where switching between an open-source provider like Keycloak and an enterprise-grade one like Entra ID was a matter of a single configuration switch, not a week of refactoring.

In this guide, I’m going to walk you through how to implement a production-ready Entra ID authentication flow within a .NET Aspire project. We’re going to look at the architectural "why," the specific Entra portal configuration, and the plumbing required to keep your local development environment sane.

GIF 1

The Identity Architecture: The "Three-Registration" Strategy

One of the most common mistakes I see in senior-level designs is trying to use a single Entra App Registration for every component in a distributed system. While it's easier to set up, it’s a security and maintenance nightmare.

In a true Clean Architecture approach, we separate concerns. In this project, I’ve structured the identity flow around three distinct registrations:

  1. The API (The Resource Server): This is the gatekeeper. It doesn't handle "logins" or UI. Its sole job is to receive a Bearer token, validate the signature against Microsoft’s keys, and check if the aud (audience) and scp (scopes) claims allow the requested action.
  2. The React App (The Public Client): This is the Next.js frontend using NextAuth.js. It performs the "heavy lifting" of the OIDC (OpenID Connect) flow. It interacts with the user, handles the redirect back from Microsoft, and securely stores the tokens.
  3. The Scalar UI (The Developer Client): Because we use Scalar for API documentation and testing, it needs its own identity. This allows developers to authenticate directly against the API without needing the React frontend running, which is a massive productivity boost.

Technical Image


Step 1: Entra Portal Configuration

To follow along with the CleanArchitecture repo, you’ll need to create three registrations in the Entra portal.

1. The API Registration

  • Name: CleanArch-API
  • Supported account types: Single Tenant Only
  • Expose an API: Define a new scope called access_as_user.
  • Application ID URI: Set this to something unique (e.g., api://your-app-id).

2. The React App Registration

  • Name: CleanArch-Web
  • Supported account types: Single Tenant Only
  • Authentication: Add a "Web" platform.
  • Redirect URI: http://localhost:65499/api/auth/callback/azure-ad
  • Secret: Generate a Client Secret (store this safely).
  • API Permissions: Select "Your APIs" and check the access_as_user permission from the API registration.

3. The Scalar Registration

  • Name: CleanArch-Scalar
  • Supported account types: Single Tenant Only
  • Authentication: Add a "Single-page application" (SPA) platform.
  • Settings: Access tokens (used for implicit flows)
  • Redirect URI: http://localhost:5049/scalar/

Step 2: Configuring the Frontend (Next.js & NextAuth)

In a .NET Aspire project, the frontend often runs as a Node.js resource. In my project, I use Next.js. The key here is the .env.local file. I've designed this to be "provider agnostic"—you can toggle between Keycloak and Entra ID.

For Entra ID, your config should look like this:

# .env.local
API_BASE_URL=http://localhost:5049/
NEXTAUTH_URL=http://localhost:65499

# Generate this using: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
NEXTAUTH_SECRET=YourSuperSecretRandomString 

# The Toggle
AUTH_PROVIDER=Entra 

# Entra ID Details
ENTRA_CLIENT_ID=<React-App-Client-ID>
ENTRA_CLIENT_SECRET=<React-App-Client-Secret>
ENTRA_TENANT_ID=<Your-Tenant-ID>
ENTRA_SCOPES=openid profile email api://<API-Client-ID>/access_as_user
ENTRA_OPENID_CONNECT=https://login.microsoftonline.com/<Tenant-ID>/v2.0/.well-known/openid-configuration

Enter fullscreen mode Exit fullscreen mode

Senior Insight: Note the ENTRA_SCOPES. We aren't just asking for openid. We are explicitly requesting the scope defined in our API registration. Without this, Entra will return an ID Token but a generic Access Token that your API will reject with a 401.


Step 3: Wiring Up the .NET API

The API sits within the CleanArchitecture.Presentation/API project. Since we are using .NET Aspire, we want our configuration to be clean and easily overridden by the AppHost.

Inside appsettings.Development.json, we configure the AzureAd section and the ScalarApi section:

{
  "Authentication": {
        "Provider": "Entra"
    },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-org.onmicrosoft.com",
    "TenantId": "...",
    "ClientId": "<API-Client-ID>",
    "Audience": "<Audience-ID>",
  },
  "ScalarApi": {    
    "ClientId": "<Scalar-Client-ID>",
    "Scopes": "openid profile email api://<Your-API-Client-ID>/access_as_user",
    "AuthorizationUrl": "<Authorisation-URL>",
  }
}

Enter fullscreen mode Exit fullscreen mode

Why Scalar?

Most .NET devs are used to Swagger. However, Scalar provides a much more robust "Try It Out" experience, especially for OAuth2/OIDC. By providing the ScalarApi config here, the Scalar UI will automatically show an "Authorize" button that initiates the Entra login flow using the Scalar App Registration.


Step 4: The .NET Aspire Orchestration

This is where the magic happens. In the AppHost project, we coordinate these services. The beauty of Aspire is that it handles the environment variable injection for us.

When you run the AppHost, it reads these settings and ensures that the API and the Web frontend are aware of each other. If you change a port in Aspire, you only have to update your Entra Redirect URIs once, rather than hunting through multiple launchSettings.json files.

GIF 2


Hard-Learned Lessons & Trade-offs

1. The Managed Identity Pivot

In local development, we use Client Secrets because they are easy. However, the moment this code moves to Azure via azd up, you should pivot to Managed Identity. .NET Aspire’s Azure components make this easy, but you must ensure your code uses DefaultAzureCredential and avoid keeping secrets in your configuration files.

2. No CORS Nightmare (Thanks to the BFF Pattern)

In a traditional SPA → API setup, the browser calls the API directly, which immediately triggers the usual CORS chaos — mismatched origins, blocked Authorization headers, and endless tweaking of Program.cs.

But in this project, the BFF (Backend‑for‑Frontend) pattern eliminates that entire class of problems.

Your React/Next.js app never calls the API from the browser.

Instead, all API traffic flows like this:

Browser → Next.js Server (BFF) → .NET API

Because the browser only communicates with the same origin (your Next.js server), there is no cross‑origin request, and therefore no CORS configuration is required in your .NET API.

The BFF handles:

  • Attaching the user’s access token securely on the server
  • Forwarding requests to the API
  • Keeping tokens out of the browser entirely
  • Ensuring the API only ever receives server‑to‑server calls

This results in a dramatically simpler and more secure setup.

Local development becomes frictionless, and production behaves exactly the same, no special CORS rules, no exposed tokens, no surprises.

3. Keycloak as a Fallback

Why did I keep Keycloak in the project? Because Entra ID requires an internet connection and an active Azure subscription. For "offline" development or lightning-fast integration tests, spinning up a Keycloak container via Aspire is a godsend. It ensures that the team can keep working even if Azure is having a bad day.

Path to Production: azd up

One of the primary reasons to use this specific project structure is the deployment story. Because this is a .NET Aspire project, you can run:

azd up

Enter fullscreen mode Exit fullscreen mode

The Azure Developer CLI will look at your AppHost, generate the necessary Bicep files, and provision your Azure Container Apps, Key Vault, and Log Analytics. Because we've separated our App Registrations, we can easily map them to environment variables in the Azure production environment, ensuring a seamless transition from "it works on my machine" to "it works in the cloud."

Conclusion

Identity is often the "final boss" of software architecture. By using .NET Aspire and following the Clean Architecture patterns laid out in this repository, you turn a complex, error-prone manual process into a repeatable, configuration-driven workflow.

**Have you made the jump to .NET Aspire yet?
What’s been your biggest challenge with Entra ID integration?

Let’s discuss in the comments.**