DEV Community

Cover image for MCP Server Authentication: OAuth 2.1 for SaaS in Node.js
Muhammad Mustafa
Muhammad Mustafa

Posted on Originally published at aisaaswithmustafa.com

MCP Server Authentication: OAuth 2.1 for SaaS in Node.js

MCP server authentication is the part most tutorials skip. My own MCP server, the AI API cost server I built and published to npm, has no login at all. It runs on your machine over stdio, it only does maths on public prices, and that is fine. But the moment you put an MCP server on a public URL in front of a SaaS product, every request is a stranger asking to read or change a customer's data.

In this guide I explain, in plain words, when an MCP server needs authentication, how the OAuth flow in the MCP spec works, how to add it to a Node.js server with the official TypeScript SDK, and the part that matters most for SaaS: mapping a token to the right tenant and role. Everything here follows the current MCP spec revision, 2026-07-28.

When an MCP server needs authentication

MCP has two common ways for a client (Claude Desktop, an IDE, an agent) to talk to a server. Which one you use decides whether you need OAuth at all.

Transport Where it runs How it authenticates
stdio On the user's own machine, started by the client No OAuth. The spec says stdio servers should read credentials from the environment, like an API key in an env variable.
Streamable HTTP On your server, reachable by URL The spec's OAuth-based authorization. Every request carries a bearer token.

My cost server is the first case. It needs no secrets, so there is nothing to protect. A SaaS MCP server is the second case. If CultureAI, the multi-tenant AI SaaS I built, offered an MCP endpoint so that a customer's AI assistant could pull workspace insights, that endpoint would need the full flow below. Nothing less is safe, because the data behind it belongs to many different companies.

How MCP server authentication works, step by step

The MCP spec does not invent a new login system. It uses OAuth 2.1 and a few related standards. Your MCP server plays the role of a resource server: it checks tokens but never issues them. A separate authorization server (Auth0, Clerk, Keycloak, your own) handles sign-in and hands out tokens.

Person approving a sign-in request in a browser to connect an AI assistant to a SaaS account

The user signs in once in the browser; after that the AI client sends a token with every MCP request.

Here is the flow, in the order it happens:

  1. The client calls your MCP endpoint without a token. Your server answers 401 with a WWW-Authenticate header that points to a metadata URL, for example Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource".
  2. The client reads your Protected Resource Metadata. This small JSON document (defined in RFC 9728) says which authorization server issues tokens for you. MCP servers must publish it.
  3. The client discovers the authorization server. It reads that server's own metadata, through OAuth Authorization Server Metadata or OpenID Connect Discovery.
  4. The client gets a client ID. The spec prefers Client ID Metadata Documents, where the client ID is a URL the client controls. Pre-registration is also allowed. Dynamic Client Registration is now marked as deprecated and kept only for older setups.
  5. The user signs in. The client opens the browser for a normal authorization code flow with PKCE (a one-time secret that stops a stolen code from being used). The request includes a resource parameter that names your MCP server exactly.
  6. The client calls you again with the token in an Authorization: Bearer header on every request. Tokens must never go in the URL query string.

The two rules people miss

Check the audience. Your server must accept only tokens that were issued for it. That is what the resource parameter (RFC 8707) is for. If you skip this check, a token a user gave to some other app on the same identity provider could be replayed against your MCP server.

No token passthrough. Your MCP server must not take the client's token and forward it to another API. If your tools call a downstream service, they use the server's own credentials for it. Forwarding tokens breaks audit trails and lets one leaked token travel further than it should.

My opinion after building auth into several SaaS apps: do not write your own authorization server for this. Use the identity provider you already have, and check its docs for what MCP clients need, mainly PKCE, resource indicators and a supported way to register clients. Your job is the resource server side, and that is small.

Adding authentication to a Node.js MCP server

The official TypeScript SDK v2 (stable since July 2026) has the pieces you need in @modelcontextprotocol/express and @modelcontextprotocol/server. The SDK does the HTTP part: the 401 challenge, the metadata endpoint and the 403 for missing scopes. You write one function, verifyAccessToken, that decides if a token is real.

import {
  createMcpExpressApp,
  requireBearerAuth,
  getOAuthProtectedResourceMetadataUrl,
  mcpAuthMetadataRouter,
} from "@modelcontextprotocol/express";
import { createMcpHandler, OAuthError, OAuthErrorCode } from "@modelcontextprotocol/server";
import { toNodeHandler } from "@modelcontextprotocol/node";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { buildServer } from "./server.js"; // registers your tools

const ISSUER = "https://auth.example.com/";
const mcpServerUrl = new URL("https://mcp.example.com/mcp");
const jwks = createRemoteJWKSet(new URL(`${ISSUER}.well-known/jwks.json`));

async function verifyAccessToken(token) {
  try {
    const { payload } = await jwtVerify(token, jwks, {
      issuer: ISSUER,
      audience: mcpServerUrl.href, // only tokens issued for this server
    });
    return {
      token,
      clientId: payload.client_id ?? payload.azp,
      scopes: String(payload.scope ?? "").split(" ").filter(Boolean),
      expiresAt: payload.exp, // required, or every request gets a 401
      resource: mcpServerUrl,
      extra: { userId: payload.sub },
    };
  } catch {
    throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid or expired token");
  }
}

const oauthMetadata = await fetch(`${ISSUER}.well-known/oauth-authorization-server`)
  .then((res) => res.json());

const app = createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ["mcp.example.com"] });
app.use(mcpAuthMetadataRouter({ oauthMetadata, resourceServerUrl: mcpServerUrl }));

const auth = requireBearerAuth({
  verifier: { verifyAccessToken },
  requiredScopes: ["mcp"],
  resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
  expectedResource: mcpServerUrl,
});

const node = toNodeHandler(createMcpHandler(buildServer));
app.all("/mcp", auth, (req, res) => void node(req, res, req.body));
app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

A few details from the SDK docs that are easy to get wrong:

  • Always return expiresAt. If it is missing, the SDK treats the token as invalid.
  • Throw OAuthError with InvalidToken for bad tokens. Any other error becomes a 500, and the client will not know it should sign in again.
  • Upgrade the two packages together. The docs note that @modelcontextprotocol/express 2.0.1 does not pass expectedResource through, so match its version with @modelcontextprotocol/server.
  • Still on v1? My own server uses @modelcontextprotocol/sdk 1.x. There, requireBearerAuth lives at @modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js, but v1 only covers the spec up to the 2025-11-25 revision.

The scope and claim names in the example (scope, client_id, azp) depend on your identity provider. Some use scp instead. Read one real token from your provider before you trust the mapping.

Mapping tokens to tenants and roles

This is where SaaS products get it wrong. A valid token proves who the user is. It does not prove which workspace they are allowed to touch in this call. That decision is still yours, inside each tool.

Two colleagues reviewing which team members can access a SaaS workspace on a laptop

The token says who is calling; the workspace and role still come from your own database.

Never trust a workspace ID from the model

Tool arguments are written by an AI model, and a model can be steered by text in a document it read. So I never let a tool argument pick the tenant. The tool reads the user from the token, looks up their membership, and only then runs the query.

server.registerTool(
  "get_workspace_insights",
  { description: "Read this month's insights for the caller's workspace", inputSchema: {} },
  async (args, ctx) => {
    const caller = ctx.http?.authInfo; // undefined over stdio
    if (!caller) throw new Error("Authentication required");

    const membership = await memberships.findOne({ userId: caller.extra.userId });
    if (!membership) throw new Error("No workspace for this user");

    const insights = await getInsights(membership.workspaceId); // tenant from the database
    return { content: [{ type: "text", text: JSON.stringify(insights) }] };
  }
);
Enter fullscreen mode Exit fullscreen mode

Use scopes for actions, roles for data

I keep two layers. Scopes say what the AI client may do at all, for example insights:read or reports:write. Roles in your own database say what this user may do inside their workspace, for example owner or member. A write tool should need both: the scope on the token, and a role that allows the action.

For per-tool scopes, the SDK has requireScopes. When a token lacks a scope, the server answers 403 with error="insufficient_scope" and the scopes it needs. A good client then asks the user to approve the extra scope and retries. Ask for the smallest set of scopes at first and add more only when a tool needs them.

Keep your usage limits in the loop

One thing I learned from CultureAI: an MCP client is just another way to spend your money. CultureAI gives every workspace a monthly AI token budget from its plan and reserves tokens before each AI call, so parallel calls cannot overshoot it. Any MCP tool that triggers an AI call should go through that same budget check. Otherwise an agent that loops on a tool becomes the most expensive user you have. My OpenAI, Claude and Gemini API pricing guide shows how to turn token rates into cost per user.

Testing MCP server authentication before launch

Before any real client connects, I would check these by hand with curl:

  1. Call /mcp with no token. Expect 401 and a WWW-Authenticate header with resource_metadata.
  2. Open the metadata URL. It should list your authorization server.
  3. Send a token issued for a different API on the same provider. Expect 401. If it passes, your audience check is broken.
  4. Send a valid token without a needed scope. Expect 403 with insufficient_scope.
  5. Sign in as a user from workspace A and try to read workspace B. You should get nothing, whatever arguments you send.
  6. Check your logs. Tokens should never appear in them.

Then connect a real MCP client and go through the browser sign-in once, the same way I tested my stdio server inside a real AI app before publishing it.

What I would do first

If you are adding MCP to a SaaS product, start small. Ship a read-only MCP server first, with one or two scopes, audience checks and tenant lookup from the database. Add write tools later, behind narrower scopes and the human approval steps from my MCP server security checklist. If you are still deciding whether you need MCP at all, my comparison of MCP and REST APIs for AI agents covers that choice.

Authentication is the boring part of MCP, and it is the part that decides whether you can let customers connect their AI tools to your product at all. If you want help designing it for your SaaS, get in touch, or see how I build AI SaaS products.


I first published this on my blog: MCP Server Authentication: OAuth 2.1 for SaaS in Node.js.

Top comments (0)