|
1 | | -from .exceptions import ( |
2 | | - MCPAuthException as MCPAuthException, |
3 | | - MCPAuthConfigException as MCPAuthConfigException, |
4 | | - AuthServerExceptionCode as AuthServerExceptionCode, |
5 | | - MCPAuthAuthServerException as MCPAuthAuthServerException, |
6 | | - BearerAuthExceptionCode as BearerAuthExceptionCode, |
7 | | - MCPAuthBearerAuthExceptionDetails as MCPAuthBearerAuthExceptionDetails, |
8 | | - MCPAuthBearerAuthException as MCPAuthBearerAuthException, |
9 | | - MCPAuthJwtVerificationExceptionCode as MCPAuthJwtVerificationExceptionCode, |
10 | | - MCPAuthJwtVerificationException as MCPAuthJwtVerificationException, |
11 | | -) |
| 1 | +import logging |
| 2 | +from typing import Any, Literal, Union |
| 3 | + |
| 4 | +from .middleware.create_bearer_auth import BaseBearerAuthConfig, BearerAuthConfig |
| 5 | +from .types import VerifyAccessTokenFunction |
| 6 | +from .config import MCPAuthConfig |
| 7 | +from .exceptions import MCPAuthAuthServerException, AuthServerExceptionCode |
| 8 | +from .utils import validate_server_config |
| 9 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 10 | +from starlette.responses import JSONResponse |
12 | 11 |
|
13 | 12 |
|
14 | 13 | class MCPAuth: |
15 | | - def __init__(self): |
16 | | - self.config = None |
| 14 | + """ |
| 15 | + The main class for the mcp-auth library, which provides methods for creating middleware |
| 16 | + functions for handling OAuth 2.0-related tasks and bearer token auth. |
| 17 | +
|
| 18 | + See Also: https://mcp-auth.dev for more information about the library and its usage. |
| 19 | +
|
| 20 | + :param config: An instance of `MCPAuthConfig` containing the server configuration. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, config: MCPAuthConfig): |
| 24 | + result = validate_server_config(config.server) |
| 25 | + |
| 26 | + if not result.is_valid: |
| 27 | + logging.error( |
| 28 | + "The authorization server configuration is invalid:\n" |
| 29 | + f"{result.errors}\n" |
| 30 | + ) |
| 31 | + raise MCPAuthAuthServerException( |
| 32 | + AuthServerExceptionCode.INVALID_SERVER_CONFIG, cause=result |
| 33 | + ) |
| 34 | + |
| 35 | + if len(result.warnings) > 0: |
| 36 | + logging.warning("The authorization server configuration has warnings:\n") |
| 37 | + for warning in result.warnings: |
| 38 | + logging.warning(f"- {warning}") |
| 39 | + |
| 40 | + self.config = config |
| 41 | + |
| 42 | + def metadata_response(self) -> JSONResponse: |
| 43 | + """ |
| 44 | + Returns a response containing the server metadata in JSON format with CORS support. |
| 45 | + """ |
| 46 | + server_config = self.config.server |
| 47 | + |
| 48 | + response = JSONResponse( |
| 49 | + server_config.metadata.model_dump(exclude_none=True), |
| 50 | + status_code=200, |
| 51 | + ) |
| 52 | + response.headers["Access-Control-Allow-Origin"] = "*" |
| 53 | + response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS" |
| 54 | + return response |
| 55 | + |
| 56 | + def bearer_auth_middleware( |
| 57 | + self, |
| 58 | + mode_or_verify: Union[Literal["jwt"], VerifyAccessTokenFunction], |
| 59 | + config: BaseBearerAuthConfig = BaseBearerAuthConfig(), |
| 60 | + jwt_options: dict[str, Any] = {}, |
| 61 | + ) -> type[BaseHTTPMiddleware]: |
| 62 | + """ |
| 63 | + Creates a middleware that handles bearer token authentication. |
| 64 | +
|
| 65 | + :param mode_or_verify: If "jwt", uses built-in JWT verification; or a custom function that |
| 66 | + takes a string token and returns an `AuthInfo` object. |
| 67 | + :param config: Configuration for the Bearer auth handler, including audience, required |
| 68 | + scopes, etc. |
| 69 | + :param jwt_options: Optional dictionary of additional options for JWT verification |
| 70 | + (`jwt.decode`). Not used if a custom function is provided. |
| 71 | + :return: A middleware class that can be used in a Starlette or FastAPI application. |
| 72 | + """ |
| 73 | + |
| 74 | + metadata = self.config.server.metadata |
| 75 | + if isinstance(mode_or_verify, str) and mode_or_verify == "jwt": |
| 76 | + from .utils import create_verify_jwt |
| 77 | + |
| 78 | + if not metadata.jwks_uri: |
| 79 | + raise MCPAuthAuthServerException( |
| 80 | + AuthServerExceptionCode.MISSING_JWKS_URI |
| 81 | + ) |
| 82 | + |
| 83 | + verify = create_verify_jwt( |
| 84 | + metadata.jwks_uri, |
| 85 | + options=jwt_options, |
| 86 | + ) |
| 87 | + elif callable(mode_or_verify): |
| 88 | + verify = mode_or_verify |
| 89 | + else: |
| 90 | + raise ValueError( |
| 91 | + "mode_or_verify must be 'jwt' or a callable function that verifies tokens." |
| 92 | + ) |
| 93 | + |
| 94 | + from .middleware.create_bearer_auth import create_bearer_auth |
| 95 | + |
| 96 | + return create_bearer_auth( |
| 97 | + verify, BearerAuthConfig(issuer=metadata.issuer, **config.model_dump()) |
| 98 | + ) |
0 commit comments