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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Vulnerabilities – Threatpost
有赞技术团队
有赞技术团队
小众软件
小众软件
O
OpenAI News
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
NISL@THU
NISL@THU
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
MongoDB | Blog
MongoDB | Blog
阮一峰的网络日志
阮一峰的网络日志
Hacker News: Ask HN
Hacker News: Ask HN
D
Docker
WordPress大学
WordPress大学
Security Archives - TechRepublic
Security Archives - TechRepublic
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
C
CERT Recently Published Vulnerability Notes
L
LINUX DO - 最新话题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
S
Security @ Cisco Blogs
Cloudbric
Cloudbric
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
GRAHAM CLULEY
S
Schneier on Security
T
Tor Project blog
Spread Privacy
Spread Privacy
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Fortinet All Blogs
L
Lohrmann on Cybersecurity
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
The Exploit Database - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
Apple Machine Learning Research
Apple Machine Learning Research
T
Threat Research - Cisco Blogs
T
Troy Hunt's 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 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
Adding OAuth 2.1 to your MCP server in TypeScript
GDS K S · 2026-04-30 · via DEV Community

If you're building an MCP server, sooner or later someone is going to ask: how does authentication work?

The MCP spec leaves this open. Most early servers shipped with no auth at all, or a hardcoded API key in an environment variable. That's fine for local Claude Desktop use. It falls apart the moment you publish a remote MCP server that real users connect to.

The right answer is OAuth 2.1 with PKCE, plus four RFCs that nobody enjoys reading: 9728 (Protected Resource Metadata), 8707 (Resource Indicators), 8414 (Authorization Server Metadata), and 7591 (Dynamic Client Registration). I know that sounds like a lot. Let me show you what it looks like in practice.

I'll use KavachOS, the auth library I built for AI agents. You don't have to use it. The point of this post is to show what a compliant MCP OAuth setup actually requires, and why each piece exists.

What you'll build

A Hono-based MCP server that:

  • exposes /.well-known/oauth-protected-resource (RFC 9728)
  • handles dynamic client registration so Claude Desktop can register itself (RFC 7591)
  • runs the authorization code flow with PKCE S256 (OAuth 2.1)
  • issues access tokens scoped to a specific resource indicator (RFC 8707)
  • validates incoming MCP requests against those tokens
Client                Auth Server          MCP Server
  │                       │                    │
  │  GET .well-known/...  │                    │
  ├──────────────────────────────────────────► │
  │  401 + auth metadata pointer               │
  │ ◄──────────────────────────────────────────┤
  │                       │                    │
  │  POST /register       │                    │
  ├──────────────────────►│                    │
  │  client_id            │                    │
  │ ◄─────────────────────┤                    │
  │                       │                    │
  │  /authorize (PKCE)    │                    │
  │ ◄────────────────────►│                    │
  │  code                 │                    │
  │ ◄─────────────────────┤                    │
  │                       │                    │
  │  /token (code+verif)  │                    │
  ├──────────────────────►│                    │
  │  access_token         │                    │
  │ ◄─────────────────────┤                    │
  │                       │                    │
  │  POST /mcp + bearer   │                    │
  ├──────────────────────────────────────────► │
  │                       │   200 + result     │
  │ ◄──────────────────────────────────────────┤

Enter fullscreen mode Exit fullscreen mode

Setup

npm install kavachos @kavachos/hono hono

Enter fullscreen mode Exit fullscreen mode

index.ts:

import { createKavach } from "kavachos";
import { mcpOAuth } from "kavachos/mcp";
import { createHonoAdapter } from "@kavachos/hono";
import { Hono } from "hono";

const kavach = await createKavach({
  database: { provider: "sqlite", url: "kavach.db" },
  plugins: [
    mcpOAuth({
      issuer: "https://your-mcp-server.com",
      resource: "https://your-mcp-server.com/mcp",
    }),
  ],
});

const app = new Hono();
app.route("/auth", createHonoAdapter(kavach));

Enter fullscreen mode Exit fullscreen mode

That's the auth surface. You still need an MCP handler. Wire it like this:

import { requireToken } from "kavachos";

app.post(
  "/mcp",
  requireToken({ scope: ["mcp:tools"] }),
  async (c) => {
    const agent = c.get("agent");
    const body = await c.req.json();
    // route the MCP request to your tool implementation
  },
);

Enter fullscreen mode Exit fullscreen mode

requireToken validates the bearer, checks scope, and attaches the agent identity to the request context. If the token is missing, expired, revoked, or has the wrong scope, the middleware rejects the request before your handler runs.

What each RFC actually does

RFC 9728: Protected Resource Metadata

When Claude Desktop tries to connect to a remote MCP server, it does not know where the OAuth endpoints are. RFC 9728 fixes that. You expose a .well-known/oauth-protected-resource endpoint that points the client at the authorization server.

GET /.well-known/oauth-protected-resource

Enter fullscreen mode Exit fullscreen mode

{
  "resource": "https://your-mcp-server.com/mcp",
  "authorization_servers": ["https://your-mcp-server.com"],
  "scopes_supported": ["mcp:tools", "mcp:resources"]
}

Enter fullscreen mode Exit fullscreen mode

Without this, Claude Desktop has no way to discover the auth flow. The connection just fails with a confusing error.

RFC 7591: Dynamic Client Registration

You do not want every MCP user filing a ticket to get a client_id. RFC 7591 lets clients register themselves at runtime. Claude Desktop calls:

POST /register
Content-Type: application/json

{ "redirect_uris": ["http://localhost:3334/callback"] }

Enter fullscreen mode Exit fullscreen mode

You return a client_id (and optionally a client_secret). The client uses it for the auth code flow. With this in place, your MCP install is one command from the user's side, not a support email.

OAuth 2.1 with PKCE S256

OAuth 2.1 is essentially OAuth 2.0 minus the mistakes. PKCE is mandatory. The implicit flow does not exist anymore. Public clients must rotate refresh tokens.

The flow:

  1. Client generates a code_verifier (random) and a code_challenge (SHA-256 of the verifier, base64url-encoded)
  2. Client redirects to /authorize?code_challenge=...&code_challenge_method=S256&...
  3. User approves
  4. Client receives an authorization code at the redirect URI
  5. Client exchanges the code plus the original code_verifier at /token for an access token

KavachOS handles this end to end. You write zero lines of OAuth code.

RFC 8707: Resource Indicators

Without resource indicators, an access token is valid for "anything this auth server protects." That is a recipe for token leakage. RFC 8707 binds a token to a specific resource (your MCP server URL).

When Claude Desktop requests a token, it includes:

resource=https://your-mcp-server.com/mcp

Enter fullscreen mode Exit fullscreen mode

The token comes back with that resource baked in. Your MCP server validates it. A token meant for one MCP server will not work against another. This matters more than people realize once a Claude user juggles ten MCP servers from one client.

Testing the flow

npm run dev

Enter fullscreen mode Exit fullscreen mode

In another terminal:

# 1. Discover the auth server
curl http://localhost:3000/.well-known/oauth-protected-resource

# 2. Register a client
curl -X POST http://localhost:3000/register \
  -H "Content-Type: application/json" \
  -d '{"redirect_uris":["http://localhost:3334/callback"]}'

# 3. Walk the auth code flow
# The MCP Inspector from Anthropic does this end to end:
# https://github.com/modelcontextprotocol/inspector

Enter fullscreen mode Exit fullscreen mode

If your server passes the inspector, Claude Desktop connects cleanly.

What you get

Once the server ships:

  • An audit log of which agent called which tool, with which scope, at which timestamp
  • Per-agent revocation, so you can kill one client without affecting others
  • Rate limits per agent, not per IP
  • A path to enterprise SSO later, since KavachOS supports SAML and OIDC providers as the upstream identity

Common pitfalls I keep seeing

A few things I have watched teams trip on while wiring this up.

Skipping the .well-known discovery endpoint. Without it, Claude Desktop has no idea where to send the user. It returns a generic "could not connect" error and the user blames the MCP server. This endpoint costs you four lines of code; ship it first.

Hardcoding client_id for testing, then forgetting to swap it for dynamic registration. The single-tenant test setup looks identical to a production setup until the second user shows up and steamrolls the first user's client. Add dynamic registration before you share the server with anyone else.

Ignoring the resource indicator. I have seen teams treat OAuth as a generic login layer and issue tokens with no resource binding. The token then works against any MCP server in the same auth realm, which means a compromised server gets credentials valid against every other server you protect. Always bind tokens to the specific resource URL.

Not setting up token revocation early. Most teams add it after the first incident. By then they have already issued thousands of tokens, none of which they can recall cleanly. The KavachOS revocation API runs in milliseconds. Wire it before you need it.

Skipping audit logs because "we will add observability later." When the first agent does something weird, the only way to find out which token it used is the audit log. Six lines of middleware now save you a week of forensic SQL later.

A note on where MCP auth is going

The MCP spec is still moving. Recent drafts formalize the discovery flow and add elicitation (asking the user to confirm an action mid-flow). KavachOS tracks the spec, so updates land in the SDK without changes on your side.

If you want to skip the build and try it, install is one command:

npx create-kavachos-app

Enter fullscreen mode Exit fullscreen mode

Source: github.com/kavachos/kavachos. MIT.


If you ship an MCP server, what's the auth setup you actually use today: hardcoded key, an Auth0/Clerk pass-through, or something custom? Curious which trade-offs you've made and where it's biting you.