v0.166.0

plain.oauthserver

An OAuth 2.1 authorization server for Plain apps — enough to let an MCP client like Claude connect as one of your users.

Overview

You can turn any Plain app into an OAuth 2.1 authorization server. Mount two routers — the server endpoints (anywhere) and the metadata document (at the domain root, where clients look for it):

# app/urls.py
from plain.oauthserver.urls import OAuthServerRouter, OAuthWellKnownRouter
from plain.urls import Router, include


class AppRouter(Router):
    namespace = ""
    urls = (
        include("oauth/", OAuthServerRouter),
        include(".well-known/", OAuthWellKnownRouter),
    )

After uv run plain postgres sync you have authorization-code + PKCE, refresh-token rotation, revocation, client registration (hosted metadata documents or dynamic registration), and discovery metadata. The authorization flow reuses your existing plain.auth login — the user signs in and approves on a consent screen.

The driving use case is an end-user-facing MCP server: a customer adds your app as a custom connector in Claude, signs in, and the connector acts on their behalf. That flow needs OAuth — there is no bearer-token-paste path in the connector UI.

Connecting an MCP client

MCP clients self-configure over OAuth: the client hits your protected endpoint with no token, discovers this server, identifies itself (by hosted metadata document or by registering), and completes a browser login + consent — you mount the routers and the client drives the rest. The endpoint-side wiring (the resource server and the discovery challenge) lives in plain.mcp, which walks the full handshake.

Clients are public

Every client is a public client — it has no client_secret. That's the norm for MCP connectors and CLIs, which run on the user's machine and can't keep a secret. Clients are proven by PKCE on the code exchange (and by the refresh token on refresh), not a secret — so the token endpoint only advertises token_endpoint_auth_method: "none".

You rarely create clients by hand — Claude presents a hosted metadata document and other clients register themselves — but you can:

from plain.oauthserver.models import OAuthApplication

app = OAuthApplication(
    name="My CLI",
    redirect_uris="http://127.0.0.1/callback",  # space-separate multiple URIs
)
app.create()
print(app.client_id)

Redirect URIs must be HTTPS or loopback. Loopback URIs (http://127.0.0.1/..., http://localhost/...) match regardless of port, since a CLI's port isn't knowable at registration time (RFC 8252).

Dynamic client registration

RegisterView implements RFC 7591 at /oauth/register. A client POSTs its redirect_uris (and optional client_name) and gets back a client_id — always a public one. This is what lets a user paste only a URL into Claude — the client registers itself.

Registration is open, which is safe: a freshly registered client can do nothing until a real user completes the login + consent flow. Disable it with OAUTH_SERVER_ALLOW_DYNAMIC_REGISTRATION = False if you'd rather register clients yourself.

MCP has deprecated dynamic registration in favor of Client ID Metadata Documents; it stays on by default here because clients that don't support metadata documents yet still fall back to it.

Client ID Metadata Documents

Instead of registering, a client can present a URL as its client_id: an HTTPS address where it hosts a small JSON document describing itself (client_name, redirect_uris). That's a Client ID Metadata Document (CIMD, MCP SEP-991), and it's the registration method the MCP spec prefers. Claude, Claude Code, ChatGPT, and VS Code all use it when the server supports it. Claude's document lives at https://claude.ai/oauth/mcp-oauth-client-metadata, so there's nothing registered per user and no /oauth/register traffic.

Nothing to set up. The metadata document advertises client_id_metadata_document_supported, and when an authorize request arrives with a URL client_id, cimd.py fetches the document, checks that the document's own client_id is exactly that URL, and stores it as an OAuthApplication whose client_id is the URL — one row per client product, shared by everyone who uses that client. The requested redirect_uri is checked against the document's list like any other registration, and the consent screen shows the host the document came from, since the client_name inside it is self-asserted.

The fetch is the risky part, since the server is fetching a URL a stranger chose, so it's deliberately narrow:

  • HTTPS only, ASCII hostnames only (no IP literals, no localhost), and redirects are never followed.
  • Every address the host resolves to must be public, and the connection goes to one of those checked addresses. A DNS answer can't change between the check and the connection.
  • One 5-second deadline covers the whole fetch: DNS, connecting, TLS, and reading the response.
  • The body is capped at 5 KB and must arrive uncompressed.
  • Each process runs at most 8 fetches at once.

Only /oauth/authorize fetches. The token and revocation endpoints look up the stored client and never touch the network.

Documents are cached on the row for their Cache-Control lifetime, clamped to between 5 minutes and 24 hours (1 hour when there's no directive). If a refetch fails for a reason that might be temporary (a timeout, a connection error, a 5xx), the stored copy keeps working for up to 7 days and the server retries every 5 minutes. A document that's gone (404) or no longer valid fails right away.

Two settings control it:

  • OAUTH_SERVER_ALLOW_CLIENT_ID_METADATA_DOCUMENTS = False turns it off. URL client_ids become unknown clients, the flag disappears from the metadata document, and clients that were already stored can't refresh their tokens anymore (they can still revoke them).
  • OAUTH_SERVER_CLIENT_ID_METADATA_ALLOWED_HOSTS = ["claude.ai"] restricts which hosts' documents are accepted, with the same effect on clients from any other host. The default (None) accepts any public host.

Only public clients are supported, so the document has to offer none as a token endpoint auth method. A document that lists token_endpoint_auth_methods_supported gets none when it's in the list (ChatGPT's document offers none and private_key_jwt), a document with neither field is treated as none, and a document that only offers private_key_jwt or carries a client secret is rejected.

Protecting a resource

The server issues tokens; validating them is the resource server's job. validate_access_token resolves a bearer value to its live AccessToken, or returns None for unknown, expired, or revoked tokens. resource is required: it's the URL of the endpoint doing the check, and the token must have been issued for exactly that URL (RFC 8707 audience binding). The MCP spec requires this check, so a token issued for one server can't be replayed at another.

from plain.oauthserver import validate_access_token

token = validate_access_token(bearer, resource="https://myapp.com/mcp")
if token is not None:
    user = token.user

Clients name the resource when they authorize (MCP clients always do), and /authorize refuses a request without one. The token endpoint refuses a resource other than the one that was authorized.

That's the seam for any resource server. Protecting a plain.mcp endpoint? Its OAuthResourceServer mixin wraps this validator and handles the 401 challenge and resource-metadata document for you — see OAuth for MCP clients.

Endpoints

Endpoint Method Description
/.well-known/oauth-authorization-server GET Authorization server metadata (RFC 8414)
/oauth/authorize GET Consent screen (login required); a URL client_id is resolved here
/oauth/authorize POST Record the approve/deny decision
/oauth/token POST Code exchange and refresh (rotation)
/oauth/register POST Dynamic client registration (RFC 7591)
/oauth/revoke POST Revoke a token (RFC 7009)

Every authorization response, approved or denied, includes the iss parameter (RFC 9207), and the metadata document says so with authorization_response_iss_parameter_supported.

Override oauthserver/authorize.html in your app's templates to restyle the approval screen. It receives application, scope, and a params dict of the original request fields (client_id, redirect_uri, scope, state, resource, code_challenge, code_challenge_method) to re-submit as hidden inputs. It also gets client_host (the host a metadata document came from, or None), redirect_host (where the user will be sent back to), and loopback_only (True when every redirect URI points at the user's own machine).

When client_host is set, show it more prominently than application.name. The host is the one thing about the client the server has verified, and the name is whatever the document says. The default template puts the host in the heading. When loopback_only is true, warn the user, since nothing proves which local program is asking.

After the user decides, oauthserver/redirect.html sends them back to the client. It receives location (the client's redirect URI with the response parameters) and should navigate there without a script, as the default template does with a meta refresh and a link.

Models

  • OAuthApplication — a registered public client (no secret). For a metadata-document client the client_id is the document URL and metadata_fetched_at / metadata_expires_at track the cached copy.
  • AuthorizationCode — single-use code carrying the PKCE challenge and bound resource.
  • AccessToken — bearer token, stored as a SHA-256 hash so a database leak can't be replayed. Carries the granted scope and bound resource.
  • RefreshToken — hashed, expiring, and rotated on every use. Scope and resource come from its linked AccessToken.

Settings

Setting Default Description
OAUTH_SERVER_CODE_EXPIRY 600 Authorization code lifetime (seconds)
OAUTH_SERVER_ACCESS_TOKEN_EXPIRY 3600 Access token lifetime (seconds)
OAUTH_SERVER_REFRESH_TOKEN_EXPIRY 2592000 Refresh token lifetime (seconds, 30 days)
OAUTH_SERVER_ALLOW_DYNAMIC_REGISTRATION True Enable RFC 7591 registration
OAUTH_SERVER_ALLOW_CLIENT_ID_METADATA_DOCUMENTS True Accept URL client_ids (CIMD)
OAUTH_SERVER_CLIENT_ID_METADATA_ALLOWED_HOSTS None Hosts to fetch metadata from (None = any public host)
OAUTH_SERVER_SCOPES_SUPPORTED ["offline_access"] Scopes advertised in metadata

All settings can be set via PLAIN_-prefixed environment variables.

FAQs

Why is PKCE mandatory?

OAuth 2.1 requires PKCE for every authorization-code grant to prevent code-interception attacks. Only the S256 method is accepted; plain is rejected.

How are tokens stored?

Access and refresh tokens are generated, returned to the client once, and persisted only as a SHA-256 hash. Validation re-hashes the incoming bearer and looks it up — the plaintext is never on disk. Authorization codes are stored directly since they're single-use and short-lived.

How does refresh rotation work?

Using a refresh token issues a new access + refresh pair and revokes the old pair. Refresh tokens also expire. This is required for public clients and limits exposure if a token leaks.

Why does every Claude user share one client?

With a metadata document, the client_id is Claude's URL, so every person connecting from Claude presents the same client_id and shares one OAuthApplication row. That's by design — it's what removes the per-user registrations DCR accumulates. It also means "revoke this client" has to be scoped to a user: revoke by (user, application), never by application alone, or you'd log every Claude user out at once.

Which registration method will a client use?

The client picks, using what the metadata document advertises. MCP clients try a client they already have credentials for first, then a metadata document if client_id_metadata_document_supported is true, then dynamic registration if there's a registration_endpoint. With the default settings, Claude, Claude Code, ChatGPT, and VS Code use metadata documents, and clients that haven't adopted them yet (Cursor, for example) still register dynamically. Clients you create yourself as OAuthApplication rows always work.

What if the client's metadata host is down?

The stored document keeps serving for 7 days after a failed refetch, so a short outage at claude.ai doesn't stop anyone from connecting. A client the server has never seen before can't be resolved during the outage. The consent screen says so instead of redirecting.

Does the server need outbound internet access?

For metadata documents, yes. The first time a client connects (and again whenever the cached document expires), the server makes an HTTPS request to the client's host. Outbound proxies (HTTPS_PROXY) aren't used. If your servers can't reach the internet directly, turn metadata documents off and clients will fall back to dynamic registration.

Why does approving show a page instead of redirecting?

Browsers apply your CSP's form-action directive to every redirect that follows a form submission. Under the common form-action 'self', a 302 from the consent form to claude.ai gets blocked and the Approve button appears to do nothing. So the decision renders a small page that navigates to the client by itself. That navigation isn't a form submission, so it works whatever your CSP says.

Do I need to exempt OAuth paths from CSRF?

No. Non-browser clients don't send Origin / Sec-Fetch-Site, so Plain's CSRF protection skips them. The browser-driven consent POST is same-origin and protected normally.

How do expired tokens get cleaned up?

Refresh rotation issues a fresh pair on every use, so spent codes and revoked/expired tokens accumulate. The ClearExpiredOAuthTokens chore deletes them — run it on a schedule with plain chores run. It keeps an expired access token alive while a still-valid refresh token points at it, so refreshing never breaks.

Installation

Install the plain.oauthserver package from PyPI:

uv add plain-oauthserver

Add it to INSTALLED_PACKAGES (it needs plain.auth and plain.templates):

# app/settings.py
INSTALLED_PACKAGES = [
    "plain.auth",
    "plain.sessions",
    "plain.postgres",
    "plain.templates",
    "plain.oauthserver",
    ...,
]

Then sync the database:

uv run plain postgres sync