Skip to content

The v1 docs follow nauthera-server's main branch and its 0.x releases on the way to 1.0, so fields and APIs can still change.

v1

Protect an MCP server with Nauthera

Docs version v1 (main)Nauthera is pre-1.0, in a design-partner programUpdated

This guide puts a remote MCP server behind Nauthera, as the MCP authorization specification (2025-11-25) describes it: the MCP server is an OAuth resource server and Nauthera its authorization server. You need a Nauthera release with its operator running, the namespace mcp admitted to the main organization, kubectl, and an MCP server in TypeScript on the MCP SDK with Express; the examples use an issuer at https://auth.example.com and an MCP server at https://mcp.example.com/mcp. At the end, an MCP client signs its user in through the browser and calls the server with an access token issued for it alone, and the server refuses every other token. The main limit: Nauthera does not accept Client ID Metadata Documents, and its dynamic registration gives an MCP client none of the server's scopes, so you register each MCP client once and its users enter the client ID.

StepResourceWhat it does
Give the namespace an identifierHelm valuesLets mcp register APIs under https://mcp.example.com/
Register the MCP serverProtectedResourceIts URL becomes the tokens' aud; its scopes appear on the consent screen
Register the MCP clientOIDCClientA public client with PKCE, a loopback redirect and the MCP server among its resources
Serve the metadata and check tokensThe MCP server's codeRFC 9728 metadata, and every request's token checked
Connect the MCP clientThe MCP client's settingsThe client ID, then a sign-in in the browser

What the specification asks, and what Nauthera does

The MCP specification asks forNauthera
OAuth 2.1, the authorization code grant with PKCE S256The authorization code grant, with PKCE required of every public client and S256 the only method accepted
RFC 8414 or OpenID Connect discovery, with code_challenge_methods_supportedBoth documents, each with code_challenge_methods_supported: ["S256"]; an organization's issuer at /orgs/<slug> serves both under its path and in the path-inserted form the specification tries first (Endpoints)
RFC 8707 resource in the authorization and token requests, and a token bound to the MCP serverA ProtectedResource names the MCP server; a token for it carries its URL in aud, and a client gets one only if it lists the URL
Redirect URIs registered with the authorization server, and matched exactlyMatched exactly, except that a loopback redirect URI matches whatever port the client binds when it runs (RFC 8252 ยง7.3)
A client ID: preregistered, a Client ID Metadata Document, or dynamic registrationAn OIDCClient you register for the MCP client, whose ID its users enter; the specification has clients offer a way to enter one (Preregistration)

1. Give the namespace an identifier

An organization accepts a ProtectedResource only under an identifier prefix it allocates to the resource's namespace (Allocating identifiers). For the main organization, in the chart's values:

config:
  orgs:
    main:
      protected_resources:
        - namespaces: [mcp]
          identifier_prefixes: ["https://mcp.example.com/"]

For another organization, the same entry goes in its Organization's spec.protectedResources.

2. Register the MCP server

The identifier is the MCP server's URL, exactly as clients send it as resource: the specification calls it the server's canonical URI. Give it a path, as here. The server writes an empty path as /, so a token for https://mcp.example.com would name https://mcp.example.com/ in aud, while the specification has clients leave the slash off.

apiVersion: nauthera.io/v1alpha1
kind: ProtectedResource
metadata:
  name: notes-mcp
  namespace: mcp
spec:
  identifier: https://mcp.example.com/mcp
  displayName:
    en: Notes MCP server
  scopes:
    - name: notes:read
      descriptions:
        en: Read your notes
    - name: notes:write
      descriptions:
        en: Change your notes
  accessTokenTtlSeconds: 600

Once the organization registers a protected resource, a client gets tokens only for the registered resources its OIDCClient lists (Which clients get tokens for it). accessTokenTtlSeconds caps every token for the MCP server at ten minutes, whatever the client's own lifetime.

3. Register the MCP client

An MCP client runs on the user's machine and keeps no secret, so it is a public client: tokenEndpointAuthMethod: none, which always requires PKCE. It receives the code on a loopback redirect, http://localhost or http://127.0.0.1 with the path the client uses. Register the URI without a port: a loopback redirect matches whatever port the client binds, and the scheme, host and path still compare exactly.

apiVersion: nauthera.io/v1alpha1
kind: OIDCClient
metadata:
  name: notes-mcp-client
  namespace: mcp
spec:
  clientId: notes-mcp-client
  displayName: Notes MCP client
  tokenEndpointAuthMethod: none
  grantTypes:
    - authorization_code
  redirectUris:
    - http://localhost/callback
    - http://127.0.0.1/callback
  scopes:
    - notes:read
    - notes:write
  resources:
    - https://mcp.example.com/mcp
  deletionPolicy: Retain

spec.resources lists the identifier exactly as the ProtectedResource writes it. To keep the client signed in between sessions, add allowRefresh: true, the refresh_token grant and offline_access to its scopes; each refresh token rotates on use (Tokens).

kubectl apply -f notes-mcp.yaml
kubectl -n mcp get protectedresource notes-mcp       # PHASE Ready, reason Registered
kubectl -n mcp get oidcclient notes-mcp-client       # PHASE Ready, reason Registered

4. Serve the metadata and check tokens

The MCP server publishes RFC 9728 protected resource metadata, which names Nauthera as its authorization server and lists its scopes, and answers a request without a valid token with 401 and a WWW-Authenticate header that points to it. It then checks every access token itself, against the issuer's keys: the signature, typ: at+jwt (so an ID token is refused), iss, aud equal to its own URL, exp, and the scope the call needs. It never passes the token on to another API.

npm install @modelcontextprotocol/sdk express jose zod
import express from "express";
import { createRemoteJWKSet, errors, jwtVerify } from "jose";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { InvalidTokenError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
import type { OAuthTokenVerifier } from "@modelcontextprotocol/sdk/server/auth/provider.js";
import { OAuthMetadataSchema } from "@modelcontextprotocol/sdk/shared/auth.js";
import { z } from "zod";
 
const ISSUER = "https://auth.example.com";
// The ProtectedResource's spec.identifier: what MCP clients send as resource, and tokens carry in aud.
const RESOURCE = new URL("https://mcp.example.com/mcp");
const SCOPES = ["notes:read", "notes:write"];
 
// The issuer's metadata, read once at startup, and its signing keys, fetched and cached by jose.
const metadata = OAuthMetadataSchema.parse(
  await (await fetch(`${ISSUER}/.well-known/oauth-authorization-server`)).json()
);
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`));
 
const verifier: OAuthTokenVerifier = {
  async verifyAccessToken(token) {
    try {
      const { payload } = await jwtVerify(token, jwks, {
        issuer: ISSUER,
        audience: RESOURCE.href,
        typ: "at+jwt", // an ID token is refused
        algorithms: ["ES256"],
      });
      return {
        token,
        clientId: String(payload.client_id),
        scopes: typeof payload.scope === "string" ? payload.scope.split(" ") : [],
        expiresAt: payload.exp,
        resource: RESOURCE,
      };
    } catch (error) {
      // Answered as 401 invalid_token; anything else would be a 500.
      if (error instanceof errors.JOSEError) throw new InvalidTokenError(error.message);
      throw error;
    }
  },
};
 
function notesServer(): McpServer {
  const server = new McpServer({ name: "notes", version: "1.0.0" });
  server.registerTool(
    "list-notes",
    { title: "List notes", description: "The caller's notes.", inputSchema: { tag: z.string().optional() } },
    async ({ tag }, { authInfo }) => ({
      content: [{ type: "text", text: `Notes${tag ? ` tagged ${tag}` : ""} for ${authInfo?.clientId}` }],
    })
  );
  return server;
}
 
const app = express();
app.use(express.json());
 
// RFC 9728: /.well-known/oauth-protected-resource/mcp names the issuer and the scopes.
app.use(
  mcpAuthMetadataRouter({
    oauthMetadata: metadata,
    resourceServerUrl: RESOURCE,
    scopesSupported: SCOPES,
    resourceName: "Notes",
  })
);
 
const auth = requireBearerAuth({
  verifier,
  requiredScopes: ["notes:read"],
  expectedResource: RESOURCE,
  // Sent in WWW-Authenticate on a 401, so a client finds the issuer from there.
  resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(RESOURCE),
});
 
app.post("/mcp", auth, async (req, res) => {
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  const server = notesServer();
  res.on("close", () => {
    void transport.close();
    void server.close();
  });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});
 
app.listen(3000);

mcpAuthMetadataRouter also republishes the issuer's metadata at the MCP server's own /.well-known/oauth-authorization-server, for clients written against the earlier MCP specification. The algorithm is pinned to ES256, the algorithm Nauthera signs access tokens with whenever an EC key is configured (keys.default_alg); keep it that way.

The 401 names the scopes in requiredScopes, and a client asks for those. A tool that writes checks notes:write in its handler, from authInfo.scopes. To have clients ask for both scopes at the first sign-in, leave requiredScopes out and check each tool's scope in its handler: without scope in the 401, a client asks for every scope the metadata lists.

Check it from outside:

curl -s https://mcp.example.com/.well-known/oauth-protected-resource/mcp | jq
curl -si -X POST https://mcp.example.com/mcp | grep -i www-authenticate
# WWW-Authenticate: Bearer error="invalid_token", ..., resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"

5. Connect the MCP client

Add the MCP server's URL, https://mcp.example.com/mcp, to the MCP client and enter the client ID notes-mcp-client. At its first request the client:

  1. gets the 401, reads the protected resource metadata, and from it Nauthera's discovery document;
  2. opens the browser at /authorize with PKCE, resource=https://mcp.example.com/mcp and the scopes the 401 names (notes:read), and the user signs in and consents;
  3. redeems the code at /token, with the same resource, for a token whose aud is the MCP server's URL;
  4. calls the MCP server with it, and signs in again when it expires.

A client that cannot take a client ID tries dynamic registration, which Nauthera refuses without an initial access token.

Notes

  • An organization's issuer. For an organization other than the main one, the issuer is https://auth.example.com/orgs/<slug>: use it as ISSUER, and allocate the identifier in that Organization.
  • Revocation. Revoking a refresh token or ending the session does not reach an access token already issued, so accessTokenTtlSeconds is how long a token outlives either.
  • Introspection. The MCP server checks tokens locally and needs no introspection client; to introspect anyway, set the ProtectedResource's introspectionClient (Tokens).
  • The prompt. Protect an MCP server has an AI assistant do these steps in your repository.