OAuth¶
Hosted assistants such as Claude.ai and ChatGPT connect to MCP servers through OAuth: the user clicks “connect”, logs in to your site, approves access, and the assistant receives tokens to call your server with.
The optional django_mcpz.oauth app provides that, as an authorization server built into your project, plus an auth callable for your MCP servers.
It implements the MCP authorization specification and the standards it draws on, in a deliberately narrow profile: the OAuth 2.1 authorization code grant with PKCE, refresh tokens, public clients only, client ID metadata documents and dynamic registration, resource indicators, and revocation.
How it works¶
When an assistant first calls your MCP server without a token, it receives a 401 response pointing at a small JSON document describing the server.
That document names your authorization server, whose own JSON document lists its endpoints, and gives the MCP server’s title, or name, for the assistant to show.
The assistant then identifies itself as an OAuth client, sends the user’s browser to your site to log in and approve access, and exchanges the resulting code for an access token and a refresh token.
From then on it calls your MCP server with Authorization: Bearer ... on every request, exactly as a bearer tokens client does, and refreshes the access token when it expires.
Tokens are opaque random strings, stored as SHA-256 digests, so a leaked database does not reveal usable credentials. Access tokens last one hour by default and refresh tokens thirty days, after which the user reconnects. Each token is bound to the MCP server URL it was issued for, scheme and host included, and rejected anywhere else.
Assistants identify themselves in one of two ways. Some register through the registration endpoint, receiving a random client ID. Others use a client ID metadata document: the client ID is an HTTPS URL, from which your server fetches a JSON document describing the client, at most once an hour per client. That fetch is the one outbound request the app makes, and it is made only from the authorize page, for logged-in users, to public addresses, without following redirects.
Setup¶
Add the app to
INSTALLED_APPSand runmigrate. It needsdjango.contrib.authanddjango.contrib.sessions, which most projects have:INSTALLED_APPS = [ ..., "django_mcpz", "django_mcpz.oauth", ..., ]
Include the app’s URLs. The endpoints go under a path of your choosing, which becomes the authorization server’s URL, and the two discovery documents go at the site root, since they live under
/.well-known/:from django.urls import include, path from example.mcp import server urlpatterns = [ path("mcp", server), path("oauth/", include("django_mcpz.oauth.urls")), path("", include("django_mcpz.oauth.wellknown")), ]
This serves
/oauth/authorize,/oauth/token,/oauth/register, and/oauth/revoke, plus the discovery documents at/.well-known/oauth-authorization-server/oauthand/.well-known/oauth-protected-resource/mcp. Those last two paths follow from the endpoints’ path and the MCP server’s path, per the RFCs, so clients can find them. Nothing needs configuring: the app reads the paths from the URLconf, and the scheme and host from each request, asbuild_absolute_uri()does. A site deployed under a path prefix, withSCRIPT_NAMEorFORCE_SCRIPT_NAME, has that prefix in all its URLs, including the two discovery paths, so with a prefix of/appthe documents are at/.well-known/oauth-authorization-server/app/oauthand/.well-known/oauth-protected-resource/app/mcp. Those live at the host root, outside the prefix, so route them to the site.Serve the site over HTTPS, with
ALLOWED_HOSTSset. OAuth requires HTTPS everywhere apart fromlocalhost, and the host is what tokens are bound to, so a request on an unexpected host must be refused, whichALLOWED_HOSTSdoes. Behind a proxy that terminates TLS, setSECURE_PROXY_SSL_HEADERso Django knows the requests were HTTPS.Pass the app’s authentication callable to your server:
from django_mcpz.oauth.auth import oauth_auth from django_mcpz.server import MCPServer server = MCPServer( name="shop", version="1.0.0", auth=oauth_auth, )
Make sure users can log in. The authorize page sends anonymous users to
LOGIN_URL, so any login flow works, including social login. Django’sLoginViewis enough if you have nothing else.Schedule the cleanup of expired codes and tokens, as covered in Cleanup.
Then add your server’s URL to the assistant as a connector, and it will take you through the login and consent pages.
The consent page¶
Every authorization shows a page naming the client, the MCP server, with its title and icon where it has them, and the user, with “Allow” and “Deny” buttons. It is shown every time, even for a client the user approved before, since anyone can register a client with any name, and the page is what lets the user notice an impostor. Requests that cannot be honoured, such as one from an unknown client, show an error page instead.
The two pages are rendered from three templates:
django_mcpz/oauth/base.htmlThe base HTML document for both pages, with
titleandcontentblocks, a link to the app’sdjango_mcpz/oauth/base.cssstatic file, acolor-schememeta tag so the pages follow the user’s light or dark colour scheme, and anoindexrobots tag.django_mcpz/oauth/authorize.htmlThe consent page. Its context holds
user,client,resource,scope,redirect_uri,redirect_host, andredirect_is_local, the last being whether the client is redirecting tolocalhost. For the MCP server it holdsserver_title, its title or else its name, andserver_iconandserver_icon_dark, the icon to show and a dark-scheme alternative, each adictwith asrcURL, orNone. It must keep a form that posts adecisionfield ofallowordeny, with a CSRF token.django_mcpz/oauth/error.htmlThe error page, with
erroranddescriptionin its context.
Override them as you would any app’s templates, as covered in Django’s “Overriding templates” documentation: put files of the same names in a directory listed in your TEMPLATES setting’s DIRS, or in an app listed before django_mcpz.oauth in INSTALLED_APPS.
To restyle both pages at once, override only the base template, for example with one that extends your site’s own base template and fills in its blocks.
The pages are served with a Content-Security-Policy header of frame-ancestors 'none', so they cannot be shown inside a frame on another page.
On Django 6.0 and later with ContentSecurityPolicyMiddleware installed, the header is instead built from your SECURE_CSP policy with its frame-ancestors directive replaced, so the rest of your policy applies to the pages too.
Serving developer tools too¶
Developer tools like Claude Code send a pasted bearer token rather than going through OAuth, as covered in Which clients can use bearer tokens.
To serve both kinds of client from one server, write an auth callable that accepts a token from either app, returning the OAuth challenge when neither matches:
from django_mcpz.oauth.auth import oauth_auth
from django_mcpz.server import MCPServer
from django_mcpz.bearer_tokens.auth import token_auth
def either_auth(request):
if token_auth(request) is None:
return None
return oauth_auth(request)
server = MCPServer(
name="shop",
version="1.0.0",
auth=either_auth,
)
Managing clients and tokens¶
The admin lists clients, access tokens, and refresh tokens, with an action to revoke tokens. Revoking a user’s refresh token cuts the assistant off at the next refresh. Deactivating the user cuts it off at the next request, and so does revoking their access tokens. Assistants also revoke their own tokens when the user disconnects, through the revocation endpoint.
Expired and revoked codes and tokens, and clients that registered but never obtained a token, stay in the database until cleared. Clear them periodically, as covered in Cleanup.
Settings¶
All optional.
- MCPZ_OAUTH_ACCESS_TOKEN_LIFETIME¶
A timedelta, default one hour.
- MCPZ_OAUTH_REFRESH_TOKEN_LIFETIME¶
A timedelta, default thirty days.
- MCPZ_OAUTH_DYNAMIC_REGISTRATION¶
Default True.
Whether clients may register themselves through the registration endpoint.
The MCP specification prefers client ID metadata documents, which need no registration, but the hosted assistants still register dynamically, so leave this on unless you know your clients do not need it.
Private sites¶
Adding the app exposes a few new URLs on your site: the four endpoints under the path you chose, and the two discovery documents under /.well-known/.
If your site is meant to be hard to find, here is what they reveal to someone who does not already know your MCP server’s URL.
The discovery documents are served only for real paths.
Asking for /.well-known/oauth-protected-resource with any path that is not an MCP server’s, or /.well-known/oauth-authorization-server with any path that is not the one you included the endpoints under, gets a plain 404, the same as any unknown URL on a Django site.
So a client has to know your MCP server’s URL first, and the discovery documents then tell it where the endpoints are, nothing more.
Since both paths are yours to choose, the endpoints can sit under the same unguessable prefix as everything else.
The one thing to check is LOGIN_URL.
The authorize page sends anonymous users there, so if your login page is at a URL you would rather not reveal, such as an admin mounted at a secret path, point LOGIN_URL at a login page you are happy to show.
Tested clients¶
The test suite runs the whole flow with the official MCP Python SDK client against a live server, through dynamic registration and through a client ID metadata document, including refreshing tokens.
The flow has also been run by hand with mcp-remote, the bridge that many desktop clients use to reach remote servers, and with Claude Code calling tools through it.
Before relying on a hosted assistant, connect it to your own server once and go through the login and consent pages, since each assistant’s OAuth client has its own quirks.
Limitations¶
The app implements the parts of OAuth that MCP clients use, and nothing else. In particular:
Clients are public: there are no client secrets. MCP clients run on users’ machines or in the assistants’ browsers, where a secret could not be kept, so the protection comes from PKCE and exact redirect URIs instead.
The only ways to obtain a token are the authorization code grant, meaning the login and consent flow, and refreshing. There is no client credentials grant for machine-to-machine access, no device grant, and no OpenID Connect.
Scopes are accepted, shown on the consent page, and stored on tokens, but not interpreted. A token grants the same access as its user has, restricted per tool with Per-tool permissions if needed.
The endpoints send no CORS headers, since assistants and developer tools call them from servers or native code, not from web pages. A browser-based MCP client would need them: install
django-cors-headersand allow the endpoints and the/.well-known/paths.