Why an MCP server needs its own authorization server
In MCP OAuth, the MCP server is an OAuth resource server. It accepts access tokens; it does not log users in. That split is what lets a desktop assistant or a code editor reach a hosted MCP endpoint without ever holding a platform password.
The MCP authorization specification makes the split explicit. MCP servers MUST implement protected resource metadata, clients MUST use it to find the authorization server, and authorization servers MUST implement OAuth 2.1 with appropriate protections for public clients. A server that only checks an API key is not doing MCP authorization; it is doing API keys with an MCP-shaped endpoint on top.
The app already had sessions, memberships and an account model. The MCP endpoint sits on a different host and serves clients that cannot share a browser cookie. Extending the session model would have meant inventing a cross-host cookie or copying session tokens into a query string. A separate authorization grant is the smaller, safer piece of work.
The seven endpoints and what each one does
The package is framework-agnostic: every route is a (request: Request) => Promise<Response> handler, and createOAuthServer(...).handle routes by pathname. That made it mountable as one catch-all route without pulling the framework into the auth code.
| Endpoint | Purpose | Spec |
|---|---|---|
GET /.well-known/oauth-protected-resource |
Says which authorization server protects this MCP endpoint | RFC 9728 |
GET /.well-known/oauth-authorization-server |
Lists endpoints, grant types and scopes | RFC 8414 |
POST /oauth/register |
Registers a client and returns a client_id |
RFC 7591 |
GET /oauth/authorize |
Validates the request and returns a consent view | OAuth 2.1 |
POST /oauth/authorize/decision |
Approves or denies, with decision=approve|deny |
OAuth 2.1 |
POST /oauth/token |
authorization_code and refresh_token grants |
OAuth 2.1 |
POST /oauth/revoke |
Revokes the whole grant family, not one token | RFC 7009 |
Two details matter more than the list. First, the metadata is split across hosts: the MCP host serves protected-resource metadata, the app host serves authorization-server metadata. That is normal for RFC 9728, and it is why the resource document names the authorization server rather than assuming the same origin. Second, the consent page is not in the package. GET /oauth/authorize returns JSON for the page to render, which keeps HTML and session cookies in the web app and keeps the token machinery testable without a browser.
PKCE, codes and token lifetimes
PKCE S256 is mandatory and plain is rejected. RFC 7636 makes S256 mandatory to implement on the server and permits plain only for clients that cannot do better; the OAuth 2.1 draft goes further and removes the plain transformation entirely. Rejecting plain is therefore the forward-compatible choice, not a preference.
The lifetimes are deliberately short on the code and long on the refresh token:
| Artifact | Lifetime | Reuse |
|---|---|---|
| Authorization code | 5 minutes | Single use |
| Access token | 1 hour | Bearer, per request |
| Refresh token | 30 days | Rotates on every use |
Five minutes is half the 10-minute maximum RFC 6749 recommends. The cost is small: a consent screen that sits open for six minutes fails once and the client retries. The benefit is that a leaked code is useless almost immediately, which matters because the code travels through a browser redirect.
Refresh tokens rotate on every use, and the server keeps the family relationship. When a used code arrives twice, or a refresh token that was already rotated or revoked arrives again, every token and unused code in that grant family is revoked. RFC 9700 describes exactly this pattern: rotation alone only tells you a token leaked, revoking the family is what stops the attack. The legitimate client is forced to reauthorize, which is the correct outcome when two parties hold the same credential.
Dynamic registration without vendor impersonation
Dynamic client registration lets an MCP client obtain a client_id at runtime instead of asking a person to paste one. RFC 7591 defines the registration request and response; the server stores the redirect URIs, the grant types and the scope the client asked for.
Registration is open by design, which creates a naming problem. A client can call itself anything, including the name of a well-known assistant vendor, and the consent screen will show that name to the person approving the grant. The check that closes this is narrow: if a registration claims a known vendor name and its redirect host is outside that vendor’s domains, registration is refused. A client that genuinely belongs to the vendor keeps its name; a client borrowing the name to make a phishing consent screen look familiar does not get a registration at all.
Redirect URIs are matched exactly against what was registered, with https:// required except for http://localhost and http://127.0.0.1, and no fragments or embedded credentials. Exact matching is the OAuth 2.1 rule, and it removes the partial-match behaviour that older implementations sometimes used.
DCR versus Client ID Metadata Documents
Both MCP revisions prefer metadata documents; the difference is that the 2026-07-28 revision names DCR as deprecated, while the 2025-11-25 revision treats it as an equal option.
| Dynamic client registration (RFC 7591) | Client ID Metadata Documents | |
|---|---|---|
| Where client identity lives | A row in the authorization server’s database | A JSON document the client hosts at an HTTPS URL |
| Server storage per client | Required | None |
| Registration step | POST /oauth/register |
None; the client_id is the URL |
| Abuse control | Server-side checks on names and redirect hosts | Server fetches and validates the document |
| MCP 2025-11-25 | MAY support | SHOULD support |
| MCP 2026-07-28 | MAY, deprecated | SHOULD support |
Which should you choose? For a new server in late 2026, implement Client ID Metadata Documents first and add RFC 7591 only if you must serve clients that cannot host a metadata document. The email platform’s server ships DCR and documents it as the connector path; the vendor-impersonation check is what makes an open registration endpoint defensible. If the same endpoint were started today, CIMD would be the first path and DCR the compatibility shim.
Consent that cannot be framed or confused
The consent screen is the only place a person sees what a connector is asking for, so the page is treated as part of the security boundary rather than as UI. Every authorize and decision response sends X-Frame-Options: DENY, Content-Security-Policy: frame-ancestors 'none', Cache-Control: no-store and Referrer-Policy: no-referrer. Clickjacking a consent screen is an old attack with a known fix; the fix is one header and it belongs on the response, not in a stylesheet.
A decision requires an OWNER or ADMIN session and a same-origin Origin header when the browser sends one. The session check is what stops a MEMBER from granting account-wide access. The Origin check is what stops a cross-site form post from approving a grant the person never saw.
Scopes are deny-by-default. Only the API scopes in the plan are accepted, the read-only set is the default, and a registered client scope can only be narrowed at consent time. That last rule matters: registration happens before a tenant is chosen, so a client cannot be trusted to have asked for the right scope for the account it eventually reaches.
The owner is emailed only when the grant includes at least one write scope. A read-only connector should not generate mail; a write connector should generate exactly one message that names the client. A failed notification never blocks authorization. That ordering is deliberate: the grant is already recorded, and turning a mail failure into a failed authorization would leave the person unable to connect an account for a reason that has nothing to do with their request.
Audience binding and token storage
The resource is bound into the authorization code and into the token. A token issued for the MCP endpoint is rejected where a different resource is expected, and a token issued for another resource is rejected here. RFC 8707 defines the resource parameter that makes this possible; without it, a token minted for one service is a bearer token for every service that trusts the same issuer.
Storage follows the same principle of not keeping what you do not need. oauth_clients, oauth_authorization_codes and oauth_tokens are plain SQL tables, and codes, access tokens, refresh tokens and client secrets are stored only as SHA-256 hex digests. The client table is global by design because registration happens before a tenant exists. Every code and token row carries account_id, and all family reads and revocations filter on it, so a token from one account cannot revoke or refresh a grant in another.
Two deployment constraints are worth stating because they are easy to get wrong. The server uses node:crypto, node:fs and pg, so it mounts on the Node.js runtime, not an edge runtime. And the default rate limiter is in-process; a multi-replica deployment must inject a Redis-backed implementation or each replica will enforce its own budget.
const token = await oauth.verifyAccessToken(rawBearerToken);
if (!token) return new Response("Unauthorized", { status: 401 });
if (!token.scopes.includes("campaigns:write")) {
return new Response("Forbidden", { status: 403 });
}
// token: { accountId, scopes, clientId }
What broke and what we changed
The first assumption broke: that the auth library would provide the OAuth server. The installed version shipped neither an mcp nor an oidcProvider plugin, so there was nothing to switch on. The server was written directly against the RFCs instead, and the design was later reused for the AI email platform. That turned out better than it looked at the time: the OAuth surface is now a package with its own tests and no dependency on the app’s auth upgrade cycle.
Three decisions followed from that:
- Codes last 5 minutes, not the 10-minute ceiling. The RFC recommendation is a maximum, and a consent screen that sits open for longer than five minutes is usually a consent screen nobody is looking at.
- The rate limiter is an injected dependency. The default is in-process, which is fine on one container and wrong on three. Making it an argument forces the deployment question at construction time instead of at the first incident.
- Owner notification sits off the authorization path. The grant is recorded first and the email is best-effort. A mail outage should not present as a broken connector.
The part that still needs attention is the schema mirror. The OAuth tables are Prisma-managed, and packages/oauth keeps a raw schema.sql mirror so its Postgres tests can create the tables without Prisma. Two definitions of one schema will drift. The mirror is idempotent and test-only, which contains the damage, but a generated schema would remove the class of bug entirely.
Related
Frequently asked questions
Does an MCP server have to use OAuth?
No. Authorization is optional in MCP, and a stdio server should take credentials from its environment instead. It becomes close to mandatory for a hosted HTTP server that multiple people reach, because there is no other way to bind a grant to an account and revoke it later.
Can I use an API key instead of OAuth?
Yes, and this server accepts one as a Bearer token alongside OAuth access tokens. An API key is simpler for a single developer and worse for a shared connector: it is long-lived, it is copied into config files, and revoking it revokes every client at once. OAuth gives per-client grants, scopes and a revocation story.
Why require PKCE if the client is confidential?
Most MCP clients are public clients. They run on a desktop or in a browser and cannot keep a secret, so the authorization code is the only thing an attacker needs if it leaks. PKCE binds the code to a verifier that never leaves the client, which makes a stolen code useless. Requiring it for every client removes the case analysis.
What does RFC 9728 actually add?
It defines a metadata document that tells a client which authorization server protects a resource. Without it, a client has to guess the issuer from the resource URL. The MCP specification builds on it and requires the document to list at least one authorization server.
Why do authorization codes expire in five minutes?
Because a code is a bearer credential in transit through a browser redirect. RFC 6749 recommends a maximum of ten minutes; five halves the window and costs one retry when a consent screen sits idle. The code is also single-use, so the window only matters for a code that leaks before it is redeemed.
What happens when a refresh token is replayed?
The whole grant family is revoked: every access token, every refresh token and every unused authorization code issued under that grant. The client must start a new authorization flow. This is the behaviour RFC 9700 describes, and it is intentionally harsh because a replay means two parties held the same credential.
Do I need dynamic client registration?
Only if your clients cannot host a Client ID Metadata Document. CIMD is the direction the MCP specification now points, and DCR is deprecated but retained for compatibility. If you do run DCR, restrict redirect hosts and check claimed vendor names, or your consent screen becomes a phishing surface.
How do you test an OAuth server without a browser?
Split the consent page out and make the OAuth package return JSON for it. Then the authorize and decision endpoints are ordinary request handlers, and the tests can drive them directly. The package here runs a unit suite plus a Postgres repository suite against a dedicated test database, including transaction rollback.
Sources
- MCP authorization specification, revision 2026-07-28
- RFC 9728: OAuth 2.0 Protected Resource Metadata
- RFC 7591: OAuth 2.0 Dynamic Client Registration Protocol
- RFC 7636: Proof Key for Code Exchange by OAuth Public Clients
- RFC 8414: OAuth 2.0 Authorization Server Metadata
- RFC 7009: OAuth 2.0 Token Revocation
- RFC 8707: Resource Indicators for OAuth 2.0
- RFC 6749: The OAuth 2.0 Authorization Framework
- RFC 9700: Best Current Practice for OAuth 2.0 Security
- The OAuth 2.1 Authorization Framework, draft-ietf-oauth-v2-1
- MCP authorization specification, revision 2025-11-25
