Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Add subject field to AccessToken initialization (#4267)

Pierre Audonneta57f1c8b20d9
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/aws.py b/fastmcp_slim/fastmcp/server/auth/providers/aws.py
index ff6add398..7a3167ca6 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/aws.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/aws.py
@@ -86,6 +86,7 @@ class AWSCognitoTokenVerifier(JWTVerifier):
client_id=access_token.client_id,
scopes=access_token.scopes,
expires_at=access_token.expires_at,
+ subject=access_token.subject,
claims=cognito_claims,
)
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/clerk.py b/fastmcp_slim/fastmcp/server/auth/providers/clerk.py
index b6989d370..6378e5de8 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/clerk.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/clerk.py
@@ -212,6 +212,7 @@ class ClerkTokenVerifier(TokenVerifier):
client_id=aud or sub,
scopes=token_scopes,
expires_at=expires_at,
+ subject=sub,
claims={
"sub": sub,
"aud": aud,
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/discord.py b/fastmcp_slim/fastmcp/server/auth/providers/discord.py
index dec5e707f..bdb922fa2 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/discord.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/discord.py
@@ -139,6 +139,7 @@ class DiscordTokenVerifier(TokenVerifier):
client_id=client_id,
scopes=token_scopes,
expires_at=expires_at,
+ subject=user_data.get("id"),
claims={
"sub": user_data.get("id"),
"username": user_data.get("username"),
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/github.py b/fastmcp_slim/fastmcp/server/auth/providers/github.py
index b5f744297..db6718922 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/github.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/github.py
@@ -154,6 +154,7 @@ class GitHubTokenVerifier(TokenVerifier):
client_id=str(user_data.get("id", "unknown")), # Use GitHub user ID
scopes=token_scopes,
expires_at=None, # GitHub tokens don't typically expire
+ subject=str(user_data["id"]),
claims={
"sub": str(user_data["id"]),
"login": user_data.get("login"),
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/google.py b/fastmcp_slim/fastmcp/server/auth/providers/google.py
index 28d9a5beb..7a9e4ba18 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/google.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/google.py
@@ -176,6 +176,7 @@ class GoogleTokenVerifier(TokenVerifier):
client_id=sub,
scopes=token_scopes,
expires_at=expires_at,
+ subject=sub,
claims={
"sub": sub,
"aud": aud,
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/huggingface.py b/fastmcp_slim/fastmcp/server/auth/providers/huggingface.py
index 07cfaf4f3..de89372eb 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/huggingface.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/huggingface.py
@@ -134,6 +134,7 @@ class HuggingFaceTokenVerifier(TokenVerifier):
client_id=str(sub),
scopes=token_scopes,
expires_at=None,
+ subject=str(sub),
claims={
"sub": str(sub),
"name": userinfo.get("name"),
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/introspection.py b/fastmcp_slim/fastmcp/server/auth/providers/introspection.py
index 6d071d265..e11d24db6 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/introspection.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/introspection.py
@@ -287,6 +287,7 @@ class IntrospectionTokenVerifier(TokenVerifier):
client_id=str(client_id),
scopes=scopes,
expires_at=int(exp) if exp is not None else None,
+ subject=introspection_data.get("sub"),
claims=introspection_data, # Store full response for extensibility
)
self._cache.set(token, result)
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
index aedbee26f..64c8549cf 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
@@ -588,6 +588,7 @@ class JWTVerifier(TokenVerifier):
client_id=str(client_id),
scopes=scopes,
expires_at=int(exp) if exp is not None else None,
+ subject=claims.get("sub"),
claims=claims,
)
@@ -676,5 +677,6 @@ class StaticTokenVerifier(TokenVerifier):
client_id=token_data["client_id"],
scopes=scopes,
expires_at=expires_at,
+ subject=token_data.get("sub"),
claims=token_data,
)
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/workos.py b/fastmcp_slim/fastmcp/server/auth/providers/workos.py
index 7ca3b924a..bf955e821 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/workos.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/workos.py
@@ -105,6 +105,7 @@ class WorkOSTokenVerifier(TokenVerifier):
client_id=str(user_data.get("sub", "unknown")),
scopes=token_scopes,
expires_at=None, # Will be set from token introspection if needed
+ subject=user_data.get("sub"),
claims={
"sub": user_data.get("sub"),
"email": user_data.get("email"),
diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.py
index 3e056cb37..b39f36e20 100644
--- a/fastmcp_slim/fastmcp/server/dependencies.py
+++ b/fastmcp_slim/fastmcp/server/dependencies.py
@@ -618,6 +618,7 @@ def get_access_token() -> AccessToken | None:
# Optional fields
expires_at=access_token_as_dict.get("expires_at"),
resource=access_token_as_dict.get("resource"),
+ subject=access_token_as_dict.get("subject"),
claims=access_token_as_dict.get("claims") or {},
)
except Exception as e:
diff --git a/tests/server/auth/providers/test_introspection.py b/tests/server/auth/providers/test_introspection.py
index 047a3dee0..f96e13d22 100644
--- a/tests/server/auth/providers/test_introspection.py
+++ b/tests/server/auth/providers/test_introspection.py
@@ -138,6 +138,7 @@ class TestIntrospectionTokenVerifier:
assert access_token.client_id == "user-123"
assert access_token.scopes == ["read", "write"]
assert access_token.expires_at is not None
+ assert access_token.subject == "user-123"
assert access_token.claims["active"] is True
assert access_token.claims["username"] == "testuser"
@@ -372,6 +373,7 @@ class TestIntrospectionTokenVerifier:
assert access_token is not None
assert access_token.client_id == "user-456"
+ assert access_token.subject == "user-456"
async def test_client_id_defaults_to_unknown(
self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock
@@ -390,6 +392,7 @@ class TestIntrospectionTokenVerifier:
assert access_token is not None
assert access_token.client_id == "unknown"
+ assert access_token.subject is None
def test_initialization_with_client_secret_post(self):
"""Test verifier initialization with client_secret_post method."""
diff --git a/tests/server/auth/test_jwt_provider.py b/tests/server/auth/test_jwt_provider.py
index fb182dda9..5a37711d2 100644
--- a/tests/server/auth/test_jwt_provider.py
+++ b/tests/server/auth/test_jwt_provider.py
@@ -1,16 +1,23 @@
import time
from collections.abc import AsyncGenerator
from typing import Any, cast
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
import pytest
from joserfc import jwk as jose_jwk
from joserfc import jwt
from joserfc.jws import JWSRegistry
from joserfc.registry import HeaderParameter
+from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
+from starlette.requests import Request
from fastmcp import FastMCP
from fastmcp.server.auth.providers.jwt import JWKData, JWKSData, JWTVerifier, RSAKeyPair
+from fastmcp.server.dependencies import (
+ FastMCPRequestContext,
+ fastmcp_request_ctx,
+ get_access_token,
+)
from fastmcp.utilities.tests import run_server_async
from tests.utilities.httpx2_mock import HTTPXMock
@@ -337,6 +344,7 @@ class TestSymmetricKeyJWT:
assert "read" in access_token.scopes
assert "write" in access_token.scopes
assert access_token.expires_at is not None
+ assert access_token.subject == "test-user"
async def test_symmetric_token_with_different_algorithms(
self, symmetric_key_helper: SymmetricKeyHelper
@@ -482,6 +490,106 @@ class TestSymmetricKeyJWT:
assert access_token is None
+def _create_token_without_sub(
+ rsa_key_pair: RSAKeyPair,
+ *,
+ issuer: str = "https://test.example.com",
+ audience: str | None = None,
+) -> str:
+ """Sign a JWT with no 'sub' claim, to exercise the missing-subject path."""
+ payload: dict[str, str | int] = {
+ "iss": issuer,
+ "iat": int(time.time()),
+ "exp": int(time.time()) + 3600,
+ }
+ if audience:
+ payload["aud"] = audience
+ signing_key = jose_jwk.import_key(
+ rsa_key_pair.private_key.get_secret_value(), "RSA"
+ )
+ return jwt.encode({"alg": "RS256"}, payload, signing_key, algorithms=["RS256"])
+
+
+class TestJWTAccessTokenSubject:
+ """Regression tests for issue #4266.
+
+ ``get_access_token().subject`` was always ``None``, even when the
+ authorization server supplied a ``sub`` claim, because neither the
+ JWT verifier nor the dependency-layer conversion carried it through.
+ """
+
+ async def test_subject_populated_from_sub_claim(
+ self, bearer_provider: JWTVerifier, rsa_key_pair: RSAKeyPair
+ ):
+ """A JWT bearing a 'sub' claim results in a populated subject."""
+ token = rsa_key_pair.create_token(
+ subject="user-42",
+ issuer="https://test.example.com",
+ audience="https://api.example.com",
+ )
+
+ access_token = await bearer_provider.load_access_token(token)
+
+ assert access_token is not None
+ assert access_token.subject == "user-42"
+
+ async def test_subject_is_none_without_sub_claim(
+ self, bearer_provider: JWTVerifier, rsa_key_pair: RSAKeyPair
+ ):
+ """A JWT with no 'sub' claim yields subject=None instead of crashing."""
+ token = _create_token_without_sub(
+ rsa_key_pair, audience="https://api.example.com"
+ )
+
+ access_token = await bearer_provider.load_access_token(token)
+
+ assert access_token is not None
+ assert access_token.subject is None
+
+ async def test_get_access_token_returns_subject_for_realistic_jwt_request(
+ self, bearer_provider: JWTVerifier, rsa_key_pair: RSAKeyPair
+ ):
+ """End-to-end path a real authenticated request actually takes.
+
+ Mirrors ``mcp.server.auth.middleware.bearer_auth.BearerAuthBackend``,
+ which wraps whatever the ``TokenVerifier`` returns directly into
+ ``AuthenticatedUser`` and stores it on ``request.scope["user"]``.
+ ``get_access_token()`` reads that object first, before ever reaching
+ the dependency-layer conversion block - so this is the path that
+ must carry ``subject`` through for real JWT-authenticated requests.
+ """
+ token = rsa_key_pair.create_token(
+ subject="user-42",
+ issuer="https://test.example.com",
+ audience="https://api.example.com",
+ )
+ access_token = await bearer_provider.load_access_token(token)
+ assert access_token is not None
+
+ user = AuthenticatedUser(access_token)
+ request = Request({"type": "http", "user": user, "auth": MagicMock()})
+
+ ctx_token = fastmcp_request_ctx.set(
+ FastMCPRequestContext(
+ session=MagicMock(),
+ request_id="0",
+ meta=None,
+ request=request,
+ protocol_version="2025-06-18",
+ close_sse_stream=None,
+ lifespan_context=MagicMock(),
+ _srctx=MagicMock(meta=None),
+ )
+ )
+ try:
+ result = get_access_token()
+ finally:
+ fastmcp_request_ctx.reset(ctx_token)
+
+ assert result is not None
+ assert result.subject == "user-42"
+
+
class TestBearerTokenJWKS:
"""Tests for JWKS URI functionality.
diff --git a/tests/server/auth/test_static_token_verifier.py b/tests/server/auth/test_static_token_verifier.py
index 6b51edcef..bfa0f3dbb 100644
--- a/tests/server/auth/test_static_token_verifier.py
+++ b/tests/server/auth/test_static_token_verifier.py
@@ -27,6 +27,7 @@ class TestStaticTokenVerifier:
"client_id": "test-client",
"scopes": ["read", "write"],
"expires_at": None,
+ "sub": "user-42",
},
"scoped-token": {"client_id": "limited-client", "scopes": ["read"]},
}
@@ -39,12 +40,14 @@ class TestStaticTokenVerifier:
assert result.scopes == ["read", "write"]
assert result.token == "valid-token"
assert result.expires_at is None
+ assert result.subject == "user-42"
- # Test token with different scopes
+ # Test token with different scopes and no "sub" entry
result = await verifier.verify_token("scoped-token")
assert isinstance(result, AccessToken)
assert result.client_id == "limited-client"
assert result.scopes == ["read"]
+ assert result.subject is None
# Test invalid token
result = await verifier.verify_token("invalid-token")
diff --git a/tests/server/http/test_stale_access_token.py b/tests/server/http/test_stale_access_token.py
index c2cf19180..41aa450d8 100644
--- a/tests/server/http/test_stale_access_token.py
+++ b/tests/server/http/test_stale_access_token.py
@@ -11,6 +11,7 @@ from unittest.mock import MagicMock
from mcp.server.auth.middleware.auth_context import auth_context_var
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
+from mcp.server.auth.provider import AccessToken as SDKAccessToken
from starlette.requests import Request
from fastmcp.server.auth import AccessToken
@@ -166,3 +167,55 @@ class TestStaleAccessToken:
finally:
auth_context_var.reset(auth_token)
fastmcp_request_ctx.reset(request_token)
+
+
+class TestAccessTokenSubjectConversion:
+ """Regression tests for issue #4266.
+
+ When a ``TokenVerifier`` returns the SDK's own ``AccessToken`` (or any
+ object that isn't FastMCP's ``AccessToken`` subclass), ``get_access_token()``
+ converts it via ``model_dump()``. That conversion previously dropped the
+ ``subject`` field entirely.
+ """
+
+ def test_subject_carried_over_when_converting_sdk_access_token(self):
+ """A raw SDK AccessToken with a populated subject survives conversion."""
+ sdk_token = SDKAccessToken(
+ token="sdk-token",
+ client_id="test-client",
+ scopes=["read"],
+ subject="user-99",
+ )
+ user = AuthenticatedUser(sdk_token)
+ scope = {"type": "http", "user": user, "auth": MagicMock()}
+ mock_request = Request(scope)
+
+ request_token = fastmcp_request_ctx.set(_make_ctx(mock_request))
+ try:
+ result = get_access_token()
+ finally:
+ fastmcp_request_ctx.reset(request_token)
+
+ assert result is not None
+ assert not isinstance(sdk_token, AccessToken) # confirms conversion ran
+ assert result.subject == "user-99"
+
+ def test_subject_none_when_converting_sdk_access_token_without_subject(self):
+ """A raw SDK AccessToken with no subject converts cleanly to subject=None."""
+ sdk_token = SDKAccessToken(
+ token="sdk-token-no-subject",
+ client_id="test-client",
+ scopes=["read"],
+ )
+ user = AuthenticatedUser(sdk_token)
+ scope = {"type": "http", "user": user, "auth": MagicMock()}
+ mock_request = Request(scope)
+
+ request_token = fastmcp_request_ctx.set(_make_ctx(mock_request))
+ try:
+ result = get_access_token()
+ finally:
+ fastmcp_request_ctx.reset(request_token)
+
+ assert result is not None
+ assert result.subject is None