Server: Setting Up Authentication
Relevant source files
The following files were used as context for generating this wiki page:
The python-sdk provides a comprehensive framework for setting up an OAuth 2.0 Authorization Server (AS). This allows an MCP server to handle client registration, user authorization, and token issuance, enabling secure access to its resources. The implementation follows modern security standards, including the Authorization Code Grant with PKCE (Proof Key for Code Exchange).
The authentication system is designed to be modular. It consists of a core provider interface that you implement, a set of pre-built API routes that expose the OAuth endpoints, and middleware for protecting your server's resources. This design separates the OAuth protocol logic from the application-specific user and client management, which you define in the provider. The example implementation demonstrates a split between an Authorization Server and a Resource Server, aligning with RFC 9728.
Sources: examples/servers/simple-auth/README.md, src/mcp/server/auth/provider.py, src/mcp/server/auth/routes.py, src/mcp/server/auth/middleware/bearer_auth.py
Core Components
The authentication system is built around three main components: the Provider, the Routes, and the Middleware.
This diagram illustrates the relationship between the key components of the authentication system.
1. OAuth Authorization Server Provider
The OAuthAuthorizationServerProvider is an abstract base class that defines the contract for handling the storage and logic of clients, authorization codes, and tokens. You must create a concrete implementation of this class to integrate your user and client database with the authentication framework.
The provider defines methods for the entire OAuth lifecycle:
- Client Management:
get_client,register_client - Authorization Flow:
authorize,load_authorization_code - Token Exchange:
exchange_authorization_code,exchange_refresh_token - Token Management:
load_access_token,load_refresh_token,revoke_token
This class diagram shows the abstract methods that need to be implemented.
The MockOAuthProvider in the integration tests serves as a complete example of how to implement this provider.
Sources: tests/server/fastmcp/auth/test_auth_integration.py:28-220
2. Authentication Routes
The create_auth_routes function generates a set of Starlette routes that implement the standard OAuth 2.0 endpoints. It takes your provider implementation and configuration options as arguments and returns a list of Route objects that can be added to your Starlette or FastAPI application.
The following endpoints are created:
| Method | Path | Description |
|---|---|---|
GET | /.well-known/oauth-authorization-server | OAuth 2.0 Authorization Server Metadata discovery endpoint (RFC 8414). |
POST | /register | Dynamic Client Registration endpoint (RFC 7591). |
GET | /authorize | The authorization endpoint for the user to grant access. |
POST | /token | The token endpoint to exchange codes or refresh tokens for access tokens. |
POST | /revoke | Token Revocation endpoint (RFC 7009). |
Sources: src/mcp/server/auth/routes.py:61-100
Configuration
You can customize the behavior of the routes using ClientRegistrationOptions and RevocationOptions.
ClientRegistrationOptions
| Parameter | Type | Description |
|---|---|---|
enabled | bool | Enables or disables the /register endpoint. |
valid_scopes | list[str] | A list of all scopes that a client is allowed to request. |
default_scopes | list[str] | Scopes assigned to a client if none are requested during registration. |
Sources: src/mcp/server/auth/routes.py:35-41
RevocationOptions
| Parameter | Type | Description |
|---|---|---|
enabled | bool | Enables or disables the /revoke endpoint. |
Sources: src/mcp/server/auth/routes.py:44-47
3. Bearer Authentication Middleware
To protect endpoints, the framework provides ASGI middleware that validates bearer tokens. This is composed of two parts: an authentication backend and a middleware that enforces authentication.
-
BearerAuthBackend: This backend integrates with Starlette'sAuthenticationMiddleware. It is responsible for extracting the bearer token from theAuthorizationheader and validating it. It uses aProviderTokenVerifier, which in turn calls theload_access_tokenmethod on yourOAuthAuthorizationServerProviderimplementation. If the token is valid and not expired, it populatesrequest.scope["user"]with anAuthenticatedUserobject andrequest.scope["auth"]withAuthCredentials. -
RequireAuthMiddleware: This middleware should be placed after theAuthenticationMiddleware. It checks if a user is authenticated and has the required scopes for a given endpoint. If the user is not authenticated, it returns a401 Unauthorizedresponse. If the user is authenticated but lacks the necessary scopes, it returns a403 Forbiddenresponse.
This flowchart shows the token validation logic within the BearerAuthBackend.
Authorization Code Flow with PKCE
The following sequence diagram illustrates the complete OAuth 2.0 Authorization Code flow with PKCE, from client registration to token revocation, as implemented by the authentication components.
This flow is demonstrated and verified in the authentication integration tests.
Sources: tests/server/fastmcp/auth/test_auth_integration.py:470-569
Summary
The python-sdk provides a robust and flexible system for adding OAuth 2.0 capabilities to an MCP server. By implementing the OAuthAuthorizationServerProvider interface, developers can integrate their own user and client data stores. The create_auth_routes function and the bearer token middleware handle the complex protocol details, providing a secure and standards-compliant authentication and authorization solution. This modular approach allows for secure resource protection while maintaining a clean separation of concerns.