Securing Remote MCP Servers with OAuth 2.1 & Better-Auth
Why Static API Keys Fail for Multi-User AI Agents
Passing a shared root API key into an MCP server gives every prompt full database access. Instead, bind every MCP tool call to a scoped user token verified at the edge.
export async function verifyMcpBearer(request: Request, db: D1Database) {
const authHeader = request.headers.get("authorization") || "";
if (!authHeader.startsWith("Bearer ")) {
throw new Response("Unauthorized MCP client", {
status: 401,
headers: { "WWW-Authenticate": 'Bearer realm="mcp"' },
});
}
return { token: authHeader.slice(7).trim() };
}Production Architecture Takeaway
Always return a standard WWW-Authenticate header on 401 responses so spec-compliant MCP clients automatically trigger the OAuth 2.1 authorization flow.
how this course connects together.
Follow AJ from first principles to production-ready architecture.
