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

推荐订阅源

罗磊的独立博客
Forbes - Security
Forbes - Security
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
GbyAI
GbyAI
B
Blog RSS Feed
S
SegmentFault 最新的问题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
博客园 - 聂微东
F
Fortinet All Blogs
H
Hacker News: Front Page
A
About on SuperTechFans
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
Check Point Blog
V
V2EX
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News | PayPal Newsroom
Cisco Talos Blog
Cisco Talos Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
P
Privacy & Cybersecurity Law Blog
N
Netflix TechBlog - Medium
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
美团技术团队
Security Latest
Security Latest
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
Recent Announcements
Recent Announcements
The GitHub Blog
The GitHub Blog
Google Online Security Blog
Google Online Security Blog
T
The Exploit Database - CXSecurity.com

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyond Localhost: Implementing Production-Grade Entra ID Auth in .NET Aspire
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.**