π The fast, Pythonic way to build MCP servers and clients.
enhancement: Configure token introspection audiences (#5461)
Jeremiah Lowin7b91b40a3843
diff --git a/docs/servers/auth/token-verification.mdx b/docs/servers/auth/token-verification.mdxindex d7fd401e1..126ab0baa 100644--- a/docs/servers/auth/token-verification.mdx+++ b/docs/servers/auth/token-verification.mdx@@ -190,6 +190,21 @@ mcp = FastMCP(name="Protected API", auth=verifier)The verifier authenticates to the introspection endpoint using client credentials and queries it whenever a bearer token arrives. FastMCP checks whether the token is active and has sufficient scopes before allowing access.+If your authorization server returns an `aud` field, set `audience` to select tokens for your API. You can provide one audience or a list of allowed audiences. The response must contain a matching string or an array of nonempty strings with at least one match; a missing or malformed `aud` is rejected when `audience` is configured.++```python+from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier++verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.yourcompany.com/oauth/introspect",+ client_id="mcp-resource-server",+ client_secret="your-client-secret",+ audience="mcp-production-api",+)+```++The default, `audience=None`, leaves audience selection to your authorization server's introspection policy. The introspection `client_id` authenticates the request to that server; it does not set the expected token audience.+Two standard client authentication methods are supported, both defined in RFC 6749:- **`client_secret_basic`** (default): Sends credentials via HTTP Basic Auth headerdiff --git a/fastmcp_slim/fastmcp/server/auth/providers/introspection.py b/fastmcp_slim/fastmcp/server/auth/providers/introspection.pyindex e11d24db6..9ec70081d 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/introspection.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/introspection.py@@ -86,6 +86,7 @@ class IntrospectionTokenVerifier(TokenVerifier):client_auth_method: ClientAuthMethod = "client_secret_basic",timeout_seconds: int = 10,required_scopes: list[str] | None = None,+ audience: str | list[str] | None = None,base_url: AnyHttpUrl | str | None = None,cache_ttl_seconds: int | None = None,max_cache_size: int | None = None,@@ -102,6 +103,9 @@ class IntrospectionTokenVerifier(TokenVerifier):uses HTTP Basic Auth header, "client_secret_post" sends credentials in POST bodytimeout_seconds: HTTP request timeout in seconds (default: 10)required_scopes: Required scopes for all tokens (optional)+ audience: Expected audience or list of allowed audiences. When set,+ the response must include a matching string or array of strings+ in `aud`. None leaves audience selection to the authorization server.base_url: Base URL for TokenVerifier protocolcache_ttl_seconds: How long to cache introspection results in seconds.Caching is disabled by default (None) to preserve real-time@@ -138,6 +142,14 @@ class IntrospectionTokenVerifier(TokenVerifier):)self.client_auth_method: ClientAuthMethod = client_auth_method+ if audience is not None:+ audiences = [audience] if isinstance(audience, str) else audience+ if not audiences or any(+ not isinstance(value, str) or not value for value in audiences+ ):+ raise ValueError("audience must contain nonempty strings")+ self.audience = audience+self.timeout_seconds = timeout_secondsself._http_client = http_clientself.logger = get_logger(__name__)@@ -265,6 +277,28 @@ class IntrospectionTokenVerifier(TokenVerifier):)return None+ if self.audience is not None:+ aud = introspection_data.get("aud")+ token_audiences = [aud] if isinstance(aud, str) else aud+ expected_audiences = (+ [self.audience]+ if isinstance(self.audience, str)+ else self.audience+ )+ if (+ not isinstance(token_audiences, list)+ or not token_audiences+ or any(+ not isinstance(value, str) or not value+ for value in token_audiences+ )+ or not any(+ value in token_audiences for value in expected_audiences+ )+ ):+ self.logger.debug("Token introspection audience mismatch")+ return None+# Extract scopesscopes = self._extract_scopes(introspection_data)diff --git a/tests/server/auth/providers/test_introspection_audience.py b/tests/server/auth/providers/test_introspection_audience.pynew file mode 100644index 000000000..fc21c4344--- /dev/null+++ b/tests/server/auth/providers/test_introspection_audience.py@@ -0,0 +1,128 @@+"""Audience selection for introspected tokens."""++from typing import Any++import pytest+from pydantic import AnyHttpUrl++from fastmcp.server.auth import RemoteAuthProvider+from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier+from tests.utilities.httpx2_mock import HTTPXMock+++ ("expected", "claim", "accepted"),+ [+ ("calendar", "calendar", True),+ ("calendar", ["notes", "calendar"], True),+ (["calendar", "notes"], "notes", True),+ (["calendar", "notes"], ["tasks", "notes"], True),+ ("calendar", "calendar-extra", False),+ ("calendar", "notes", False),+ ("calendar", ["notes"], False),+ (["calendar", "notes"], ["tasks"], False),+ ("calendar", None, False),+ ("calendar", [], False),+ ("calendar", 1, False),+ ("calendar", True, False),+ ("calendar", {"calendar": True}, False),+ ("calendar", ["calendar", 1], False),+ ("calendar", ["calendar", ""], False),+ ],+)+async def test_configured_audiences(+ expected: str | list[str], claim: Any, accepted: bool, httpx_mock: HTTPXMock+):+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ audience=expected,+ )+ response = {"active": True, "client_id": "user-1"}+ if claim is not None:+ response["aud"] = claim+ httpx_mock.add_response(json=response)++ result = await verifier.verify_token("token")++ assert (result is not None) is accepted+ if result is not None:+ assert result.claims["aud"] == claim+ assert result.client_id == "user-1"++[email protected]("claim", [None, "notes", 1, ["notes", 1]])+async def test_default_uses_introspection_decision(claim: Any, httpx_mock: HTTPXMock):+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ )+ response = {"active": True}+ if claim is not None:+ response["aud"] = claim+ httpx_mock.add_response(json=response)++ assert await verifier.verify_token("token") is not None+++async def test_audience_mismatch_is_retried(httpx_mock: HTTPXMock):+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ audience="calendar",+ cache_ttl_seconds=300,+ )+ httpx_mock.add_response(json={"active": True, "aud": "notes"})+ httpx_mock.add_response(json={"active": True, "aud": "calendar"})++ assert await verifier.verify_token("token") is None+ result = await verifier.verify_token("token")+ assert result is not None+ assert await verifier.verify_token("token") == result+ assert len(httpx_mock.get_requests()) == 2+++async def test_matching_audience_still_requires_scopes(httpx_mock: HTTPXMock):+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ audience="calendar",+ required_scopes=["read"],+ )+ httpx_mock.add_response(json={"active": True, "aud": "calendar", "scope": "write"})++ assert await verifier.verify_token("token") is None++[email protected]("audience", ["", [], [""], ["calendar", ""]])+def test_audience_configuration_requires_nonempty_values(audience: str | list[str]):+ with pytest.raises(ValueError, match="audience"):+ IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ audience=audience,+ )+++async def test_remote_provider_uses_configured_audience(httpx_mock: HTTPXMock):+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/introspect",+ client_id="calendar-client",+ client_secret="secret",+ audience="calendar",+ )+ auth = RemoteAuthProvider(+ token_verifier=verifier,+ authorization_servers=[AnyHttpUrl("https://auth.example.com")],+ base_url="https://calendar.example.com",+ )+ httpx_mock.add_response(json={"active": True, "aud": "notes"})+ httpx_mock.add_response(json={"active": True, "aud": ["calendar", "notes"]})++ assert await auth.verify_token("notes-token") is None+ assert await auth.verify_token("calendar-token") is not None