Files
modelcontextprotocol--pytho…/docs_src/authorization/tutorial001.py
T
Max Isbey a1734460a1 Reject bearer tokens that carry no audience claim
When `AuthSettings.resource_server_url` is configured, `BearerAuthBackend`
previously ran the RFC 8707 audience comparison only for tokens whose
verifier populated `AccessToken.resource`: a token carrying no resource
indicator at all was accepted. The MCP authorization spec requires a
resource server to only accept tokens issued specifically for it, so the
gate now fails closed: a verified token with no `resource` is answered
`401 invalid_token` ("The access token carries no audience claim").
`resource_server_url=None` still means there is no audience to enforce.

For verifiers that validate the audience themselves and cannot surface
the claim (for example a JWT decoder configured with the expected
audience), the new `AuthSettings.verifier_validates_audience=True` opts
the gate out. The `AuthSettings.enforced_audience` property derives the
single value both server wirings pass to `BearerAuthBackend`, whose
signature is unchanged.

`RefreshToken` gains an optional `resource` field so an authorization
server provider can carry the original grant's audience binding through
`exchange_refresh_token`; without it every refreshed access token would
be audience-unbound and rejected by the hardened gate.

The docs tutorials and example servers now populate
`AccessToken.resource` (and the client-credentials demo token endpoint
honors the RFC 8707 `resource` parameter) so they pass the check they
teach. The migration guide entry for audience validation is rewritten
for the fail-closed behavior.
2026-06-27 18:53:13 +00:00

34 lines
904 B
Python

from pydantic import AnyHttpUrl
from mcp.server import MCPServer
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings
KNOWN_TOKENS = {
"alice-token": AccessToken(
token="alice-token", client_id="alice", scopes=["notes:read"], resource="http://127.0.0.1:8000/mcp"
),
}
class StaticTokenVerifier(TokenVerifier):
async def verify_token(self, token: str) -> AccessToken | None:
return KNOWN_TOKENS.get(token)
mcp = MCPServer(
"Notes",
token_verifier=StaticTokenVerifier(),
auth=AuthSettings(
issuer_url=AnyHttpUrl("https://auth.example.com"),
resource_server_url=AnyHttpUrl("http://127.0.0.1:8000/mcp"),
required_scopes=["notes:read"],
),
)
@mcp.tool()
def list_notes() -> list[str]:
"""List every note in the notebook."""
return ["Buy milk", "Ship the release"]