Skip to content

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

Migrate auth JWTs to joserfc (#4221)

Jeremiah Lowinb8c9d58d61aa
diff --git a/fastmcp_slim/fastmcp/server/auth/cimd.py b/fastmcp_slim/fastmcp/server/auth/cimd.py
index 714de99e8..98297c60a 100644
--- a/fastmcp_slim/fastmcp/server/auth/cimd.py
+++ b/fastmcp_slim/fastmcp/server/auth/cimd.py
@@ -16,6 +16,7 @@ This module provides:
from __future__ import annotations
+import base64
import json
import time
from collections.abc import Mapping
@@ -25,6 +26,8 @@ from email.utils import parsedate_to_datetime
from typing import TYPE_CHECKING, Any, Literal
from urllib.parse import urlparse
+from joserfc import jwk
+from joserfc.errors import JoseError
from pydantic import AnyHttpUrl, BaseModel, Field, field_validator
from fastmcp.server.auth.redirect_validation import matches_allowed_pattern
@@ -42,6 +45,15 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+def _jwk_to_pem(key_data: dict[str, Any]) -> str:
+ key_type = key_data.get("kty")
+ if key_type == "RSA":
+ return jwk.import_key(key_data, "RSA").as_pem().decode("utf-8")
+ if key_type == "EC":
+ return jwk.import_key(key_data, "EC").as_pem().decode("utf-8")
+ raise ValueError(f"Unsupported JWK key type: {key_type!r}")
+
+
class CIMDDocument(BaseModel):
"""CIMD document per draft-parecki-oauth-client-id-metadata-document.
@@ -629,18 +641,13 @@ class CIMDAssertionValidator:
Raises:
ValueError: If key cannot be found or extracted
"""
- import base64
- import json
-
- from authlib.jose import JsonWebKey
-
# Extract kid from token header
try:
header_b64 = token.split(".")[0]
header_b64 += "=" * (4 - len(header_b64) % 4) # Add padding
header = json.loads(base64.urlsafe_b64decode(header_b64))
kid = header.get("kid")
- except Exception as e:
+ except (IndexError, ValueError, json.JSONDecodeError) as e:
raise ValueError(f"Failed to extract key ID from token: {e}") from e
# Find matching key in JWKS
@@ -666,9 +673,8 @@ class CIMDAssertionValidator:
# Convert JWK to PEM
try:
- jwk = JsonWebKey.import_key(matching_key)
- return jwk.as_pem().decode("utf-8")
- except Exception as e:
+ return _jwk_to_pem(matching_key)
+ except (JoseError, TypeError, ValueError) as e:
raise ValueError(f"Failed to convert JWK to PEM: {e}") from e
diff --git a/fastmcp_slim/fastmcp/server/auth/jwt_issuer.py b/fastmcp_slim/fastmcp/server/auth/jwt_issuer.py
index 15996efd4..ae5c53715 100644
--- a/fastmcp_slim/fastmcp/server/auth/jwt_issuer.py
+++ b/fastmcp_slim/fastmcp/server/auth/jwt_issuer.py
@@ -9,26 +9,13 @@ from __future__ import annotations
import base64
import time
-import warnings
from typing import Any, overload
-with warnings.catch_warnings():
- # authlib.jose emits AuthlibDeprecationWarning on import; suppress it so
- # importing this module does not trigger the warning under
- # `warnings.simplefilter("error")`. The `authlib.deprecate` import lives
- # inside this block too: importing it for the first time runs
- # `warnings.simplefilter("always", AuthlibDeprecationWarning)` at module
- # scope, which would otherwise leak past `catch_warnings()` and clobber
- # the caller's filter for subsequent Authlib deprecations. See
- # jlowin/fastmcp#4098.
- from authlib.deprecate import AuthlibDeprecationWarning
-
- warnings.simplefilter("ignore", AuthlibDeprecationWarning)
- from authlib.jose import JsonWebToken
- from authlib.jose.errors import JoseError
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
+from joserfc import jwk, jwt
+from joserfc.errors import JoseError
import fastmcp
from fastmcp.utilities.logging import get_logger
@@ -113,7 +100,7 @@ class JWTIssuer:
self.issuer = issuer
self.audience = audience
self._signing_key = signing_key
- self._jwt = JsonWebToken(["HS256"])
+ self._jwt_key = jwk.import_key(signing_key, "oct")
def issue_access_token(
self,
@@ -155,8 +142,12 @@ class JWTIssuer:
if upstream_claims:
payload["upstream_claims"] = upstream_claims
- token_bytes = self._jwt.encode(header, payload, self._signing_key)
- token = token_bytes.decode("utf-8")
+ token = jwt.encode(
+ header,
+ payload,
+ self._jwt_key,
+ algorithms=["HS256"],
+ )
logger.debug(
"Issued access token for client=%s jti=%s exp=%d",
@@ -208,8 +199,12 @@ class JWTIssuer:
if upstream_claims:
payload["upstream_claims"] = upstream_claims
- token_bytes = self._jwt.encode(header, payload, self._signing_key)
- token = token_bytes.decode("utf-8")
+ token = jwt.encode(
+ header,
+ payload,
+ self._jwt_key,
+ algorithms=["HS256"],
+ )
logger.debug(
"Issued refresh token for client=%s jti=%s exp=%d",
@@ -242,7 +237,11 @@ class JWTIssuer:
"""
try:
# Decode and verify signature
- payload = self._jwt.decode(token, self._signing_key)
+ payload = jwt.decode(
+ token,
+ self._jwt_key,
+ algorithms=["HS256"],
+ ).claims
# Validate token type
token_use = payload.get("token_use", "access")
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
index 9b73e6ae9..8f49224f4 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
@@ -5,28 +5,14 @@ from __future__ import annotations
import contextlib
import json
import time
-import warnings
from dataclasses import dataclass
-from typing import Any, cast
+from typing import Any, TypeAlias, cast
import httpx
-
-with warnings.catch_warnings():
- # authlib.jose emits AuthlibDeprecationWarning on import; suppress it so
- # importing this provider does not trigger the warning under
- # `warnings.simplefilter("error")`. The `authlib.deprecate` import lives
- # inside this block too: importing it for the first time runs
- # `warnings.simplefilter("always", AuthlibDeprecationWarning)` at module
- # scope, which would otherwise leak past `catch_warnings()` and clobber
- # the caller's filter for subsequent Authlib deprecations. See
- # jlowin/fastmcp#4098.
- from authlib.deprecate import AuthlibDeprecationWarning
-
- warnings.simplefilter("ignore", AuthlibDeprecationWarning)
- from authlib.jose import JsonWebKey, JsonWebToken
- from authlib.jose.errors import JoseError
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
+from joserfc import jwk, jwt
+from joserfc.errors import JoseError
from pydantic import AnyHttpUrl, SecretStr
from typing_extensions import TypedDict
@@ -37,6 +23,27 @@ from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
+JWKKeyData: TypeAlias = dict[str, str | list[str]]
+
+
+def _import_key_for_algorithm(key: str | bytes | JWKKeyData, algorithm: str):
+ if algorithm.startswith("HS"):
+ return jwk.import_key(key, "oct")
+ if algorithm.startswith(("RS", "PS")):
+ return jwk.import_key(key, "RSA")
+ if algorithm.startswith("ES"):
+ return jwk.import_key(key, "EC")
+ raise ValueError(f"Unsupported algorithm: {algorithm}.")
+
+
+def _jwk_to_pem(key_data: JWKKeyData) -> str:
+ key_type = key_data.get("kty")
+ if key_type == "RSA":
+ return jwk.import_key(key_data, "RSA").as_pem().decode("utf-8")
+ if key_type == "EC":
+ return jwk.import_key(key_data, "EC").as_pem().decode("utf-8")
+ raise ValueError(f"Unsupported JWK key type: {key_type!r}")
+
class JWKData(TypedDict, total=False):
"""JSON Web Key data structure."""
@@ -145,12 +152,12 @@ class RSAKeyPair:
payload.update(additional_claims)
# Create JWT
- jwt_lib = JsonWebToken(["RS256"])
- token_bytes = jwt_lib.encode(
- header, payload, self.private_key.get_secret_value()
+ signing_key = _import_key_for_algorithm(
+ self.private_key.get_secret_value(), "RS256"
)
+ token = jwt.encode(header, payload, signing_key, algorithms=["RS256"])
- return token_bytes.decode("utf-8")
+ return token
def _looks_like_pem_public_key(key: str | bytes) -> bool:
@@ -282,7 +289,6 @@ class JWTVerifier(TokenVerifier):
self.jwks_uri = jwks_uri
self.ssrf_safe = ssrf_safe
self._http_client = http_client
- self.jwt = JsonWebToken([self.algorithm])
self.logger = get_logger(__name__)
# Simple JWKS cache
@@ -327,8 +333,7 @@ class JWTVerifier(TokenVerifier):
self._jwks_cache = {}
for key_data in jwks_data.get("keys", []):
key_kid = key_data.get("kid")
- jwk = JsonWebKey.import_key(key_data)
- public_key = jwk.get_public_key()
+ public_key = _jwk_to_pem(key_data)
if key_kid:
self._jwks_cache[key_kid] = public_key
@@ -364,7 +369,7 @@ class JWTVerifier(TokenVerifier):
raise ValueError(f"Failed to fetch JWKS: {e}") from e
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JWKS JSON: {e}") from e
- except (JoseError, TypeError, KeyError) as e:
+ except (JoseError, TypeError, KeyError, ValueError) as e:
self.logger.debug("JWKS key processing failed: %s", e)
raise ValueError(f"Failed to process JWKS: {e}") from e
@@ -423,7 +428,8 @@ class JWTVerifier(TokenVerifier):
verification_key = await self._get_verification_key(token)
# Decode and verify the JWT token
- claims = self.jwt.decode(token, verification_key)
+ key = _import_key_for_algorithm(verification_key, self.algorithm)
+ claims = jwt.decode(token, key, algorithms=[self.algorithm]).claims
# Extract client ID early for logging
client_id = (
diff --git a/fastmcp_slim/pyproject.toml b/fastmcp_slim/pyproject.toml
index 61b9e163c..699eface3 100644
--- a/fastmcp_slim/pyproject.toml
+++ b/fastmcp_slim/pyproject.toml
@@ -89,6 +89,7 @@ server = [
"griffelib>=2.0.0",
"jsonref>=1.1.0",
"jsonschema-path>=0.3.4",
+ "joserfc>=1.1.0",
"openapi-pydantic>=0.5.1",
"packaging>=24.0",
"py-key-value-aio[filetree,keyring,memory]>=0.4.4,<0.5.0",
diff --git a/tests/server/auth/providers/test_http_client.py b/tests/server/auth/providers/test_http_client.py
index fa6126183..1fc9b628b 100644
--- a/tests/server/auth/providers/test_http_client.py
+++ b/tests/server/auth/providers/test_http_client.py
@@ -8,6 +8,7 @@ import time
import httpx
import pytest
+from joserfc import jwk
from pytest_httpx import HTTPXMock
from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier
@@ -151,10 +152,8 @@ class TestJWTVerifierHttpClient:
httpx_mock: HTTPXMock,
):
"""When http_client is provided, JWKS fetches should use it."""
- from authlib.jose import JsonWebKey
-
# Build a JWKS response from the RSA key pair
- public_key_obj = JsonWebKey.import_key(rsa_key_pair.public_key)
+ public_key_obj = jwk.import_key(rsa_key_pair.public_key, "RSA")
jwk_dict = dict(public_key_obj.as_dict())
jwk_dict["kid"] = "test-key-1"
jwk_dict["use"] = "sig"
diff --git a/tests/server/auth/test_jwt_issuer.py b/tests/server/auth/test_jwt_issuer.py
index 9bebf1132..1f1b8d3ea 100644
--- a/tests/server/auth/test_jwt_issuer.py
+++ b/tests/server/auth/test_jwt_issuer.py
@@ -4,7 +4,7 @@ import base64
import time
import pytest
-from authlib.jose.errors import JoseError
+from joserfc.errors import JoseError
from fastmcp.server.auth.jwt_issuer import (
JWTIssuer,
diff --git a/tests/server/auth/test_jwt_provider.py b/tests/server/auth/test_jwt_provider.py
index 586d44d5b..c73e5bbf0 100644
--- a/tests/server/auth/test_jwt_provider.py
+++ b/tests/server/auth/test_jwt_provider.py
@@ -1,8 +1,11 @@
+import time
from collections.abc import AsyncGenerator
from typing import Any
from unittest.mock import patch
import pytest
+from joserfc import jwk as jose_jwk
+from joserfc import jwt
from pytest_httpx import HTTPXMock
from fastmcp import FastMCP
@@ -42,10 +45,6 @@ class SymmetricKeyHelper:
additional_claims: Any additional claims to include
algorithm: JWT signing algorithm (HS256, HS384, or HS512)
"""
- import time
-
- from authlib.jose import JsonWebToken
-
# Create header
header = {"alg": algorithm}
@@ -67,10 +66,10 @@ class SymmetricKeyHelper:
payload.update(additional_claims)
# Create JWT
- jwt_lib = JsonWebToken([algorithm])
- token_bytes = jwt_lib.encode(header, payload, self.secret)
+ signing_key = jose_jwk.import_key(self.secret, "oct")
+ token = jwt.encode(header, payload, signing_key, algorithms=[algorithm])
- return token_bytes.decode("utf-8")
+ return token
@pytest.fixture(scope="module")
@@ -433,13 +432,22 @@ class TestBearerTokenJWKS:
@pytest.fixture
def mock_jwks_data(self, rsa_key_pair: RSAKeyPair) -> JWKSData:
"""Create mock JWKS data from RSA key pair."""
- from authlib.jose import JsonWebKey
-
# Create JWK from the RSA public key
- jwk = JsonWebKey.import_key(rsa_key_pair.public_key)
- jwk_data: JWKData = jwk.as_dict()
- jwk_data["kid"] = "test-key-1"
- jwk_data["alg"] = "RS256"
+ public_key = jose_jwk.import_key(rsa_key_pair.public_key, "RSA")
+ public_key_data = public_key.as_dict()
+ kty = public_key_data["kty"]
+ n = public_key_data["n"]
+ e = public_key_data["e"]
+ assert isinstance(kty, str)
+ assert isinstance(n, str)
+ assert isinstance(e, str)
+ jwk_data = JWKData(
+ kty=kty,
+ n=n,
+ e=e,
+ kid="test-key-1",
+ alg="RS256",
+ )
return {"keys": [jwk_data]}
diff --git a/uv.lock b/uv.lock
index af19d733d..4919d76bf 100644
--- a/uv.lock
+++ b/uv.lock
@@ -991,6 +991,7 @@ server = [
{ name = "exceptiongroup" },
{ name = "griffelib" },
{ name = "httpx" },
+ { name = "joserfc" },
{ name = "jsonref" },
{ name = "jsonschema-path" },
{ name = "mcp" },
@@ -1025,6 +1026,7 @@ requires-dist = [
{ name = "httpx", marker = "extra == 'client'", specifier = ">=0.28.1,<1.0" },
{ name = "httpx", marker = "extra == 'mcp'", specifier = ">=0.28.1,<1.0" },
{ name = "httpx", marker = "extra == 'server'", specifier = ">=0.28.1,<1.0" },
+ { name = "joserfc", marker = "extra == 'server'", specifier = ">=1.1.0" },
{ name = "jsonref", marker = "extra == 'gemini'", specifier = ">=1.1.0" },
{ name = "jsonref", marker = "extra == 'server'", specifier = ">=1.1.0" },
{ name = "jsonschema-path", marker = "extra == 'server'", specifier = ">=0.3.4" },
@@ -1520,6 +1522,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/67/8a/a342b2f0251f3dac4ca17618265d93bf244a2a4d089126e81e4c1056ac50/jiter-0.13.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bb00b6d26db67a05fe3e12c76edc75f32077fb51deed13822dc648fa373bc19", size = 343768, upload-time = "2026-02-02T12:37:55.055Z" },
]
+[[package]]
+name = "joserfc"
+version = "1.6.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3b/dc/5f768c2e391e9afabe5d18e3221346deb5fb6338565f1ccc9e7c6d7befdd/joserfc-1.6.5.tar.gz", hash = "sha256:1482a7db78fb4602e44ed89e51b599d052e091288c7c532c5b694e20149dec48", size = 231881, upload-time = "2026-05-06T04:58:13.408Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/3b/ad1cb22e75c963b1f07c8a2329bf47227ce7e4361df5eb2fb101b2ce33ef/joserfc-1.6.5-py3-none-any.whl", hash = "sha256:e9878a0f8243fe7b95e11fdda81374ca9f7a689e302751579d3dfdeec559675e", size = 70464, upload-time = "2026-05-06T04:58:11.668Z" },
+]
+
[[package]]
name = "jsonref"
version = "1.1.0"