Skip to content

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

fix: Share JWKS refreshes across key lookups (#5456)

Jeremiah Lowin1aebbb927f5f
diff --git a/docs/servers/auth/token-verification.mdx b/docs/servers/auth/token-verification.mdx
index 9e55640ba..d7fd401e1 100644
--- a/docs/servers/auth/token-verification.mdx
+++ b/docs/servers/auth/token-verification.mdx
@@ -78,6 +78,8 @@ mcp = FastMCP(name="Protected API", auth=verifier)
This configuration creates a server that validates JWTs issued by `auth.yourcompany.com`. The verifier periodically fetches public keys from the JWKS endpoint and validates incoming tokens against those keys. Only tokens with the correct issuer and audience claims will be accepted.
+The verifier caches keys for one hour and shares a refresh among concurrent requests. `jwks_refresh_interval` sets the minimum time between refresh attempts, including failed attempts, and defaults to 30 seconds. A token with a newly rotated key ID may need to wait until that interval passes. Tokens using a known, fresh key continue to validate during the interval. Set `jwks_refresh_interval=0` to allow a refresh on every cache miss.
+
The `issuer` parameter ensures tokens come from your trusted authentication system, while `audience` validation prevents tokens intended for other services from being accepted by your MCP server.
`JWTVerifier` accepts RSA (`RS*` and `PS*`), ECDSA (`ES*`), and Edwards-curve (`Ed25519` and `Ed448`) signatures from JWKS endpoints. Set `algorithm` when your issuer does not use the default `RS256`:
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
index 74fb98740..5370811e7 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py
@@ -4,10 +4,12 @@ from __future__ import annotations
import contextlib
import json
+import math
import time
from dataclasses import dataclass
from typing import Any, Literal, TypeAlias, cast
+import anyio
import httpx2
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
@@ -234,6 +236,7 @@ class JWTVerifier(TokenVerifier):
base_url: AnyHttpUrl | str | None = None,
ssrf_safe: bool = False,
http_client: httpx2.AsyncClient | None = None,
+ jwks_refresh_interval: float = 30.0,
):
"""
Initialize a JWTVerifier configured to validate JWTs using either a static key or a JWKS endpoint.
@@ -254,10 +257,14 @@ class JWTVerifier(TokenVerifier):
the client is reused for JWKS fetches and the caller is responsible for
its lifecycle. When None (default), a fresh client is created per fetch.
Cannot be used with ssrf_safe=True.
+ jwks_refresh_interval: Minimum seconds between JWKS refresh attempts,
+ including failed attempts. Defaults to 30. Set to zero to refresh
+ on every cache miss. Known keys remain usable for the cache TTL.
Raises:
ValueError: If neither or both of `public_key` and `jwks_uri` are provided,
- if `algorithm` is unsupported, or if `http_client` is provided with `ssrf_safe=True`.
+ if `algorithm` is unsupported, if `http_client` is provided with
+ `ssrf_safe=True`, or if `jwks_refresh_interval` is negative or non-finite.
"""
if not public_key and not jwks_uri:
raise ValueError("Either public_key or jwks_uri must be provided")
@@ -317,6 +324,9 @@ class JWTVerifier(TokenVerifier):
self.algorithm = algorithm
self.issuer = issuer
self.audience = audience
+ if not math.isfinite(jwks_refresh_interval) or jwks_refresh_interval < 0:
+ raise ValueError("jwks_refresh_interval must be finite and non-negative")
+
self.public_key = public_key
self.jwks_uri = jwks_uri
self.ssrf_safe = ssrf_safe
@@ -327,6 +337,9 @@ class JWTVerifier(TokenVerifier):
self._jwks_cache: dict[str, str] = {}
self._jwks_cache_time: float = 0
self._cache_ttl = 3600 # 1 hour
+ self._jwks_refresh_interval = jwks_refresh_interval
+ self._jwks_last_refresh_attempt: float | None = None
+ self._jwks_refresh_lock = anyio.Lock()
async def _get_verification_key(self, token: str) -> str | bytes:
"""Get the verification key for the token."""
@@ -343,11 +356,11 @@ class JWTVerifier(TokenVerifier):
raise ValueError(f"Failed to extract key ID from token: {e}") from e
async def _get_jwks_key(self, kid: str | None) -> str:
- """Fetch key from JWKS with simple caching and SSRF protection."""
+ """Resolve a key, sharing refreshes and retaining fresh cached keys."""
if not self.jwks_uri:
raise ValueError("JWKS URI not configured")
- current_time = time.time()
+ current_time = time.monotonic()
# Check cache first
if current_time - self._jwks_cache_time < self._cache_ttl:
@@ -357,6 +370,29 @@ class JWTVerifier(TokenVerifier):
# If no kid but only one key cached, use it
return next(iter(self._jwks_cache.values()))
+ async with self._jwks_refresh_lock:
+ current_time = time.monotonic()
+ fresh = current_time - self._jwks_cache_time < self._cache_ttl
+ if fresh:
+ if kid and kid in self._jwks_cache:
+ return self._jwks_cache[kid]
+ if not kid and len(self._jwks_cache) == 1:
+ return next(iter(self._jwks_cache.values()))
+
+ if (
+ self._jwks_last_refresh_attempt is not None
+ and current_time - self._jwks_last_refresh_attempt
+ < self._jwks_refresh_interval
+ ):
+ raise ValueError(
+ "No matching fresh JWKS key; refresh available shortly"
+ )
+
+ self._jwks_last_refresh_attempt = current_time
+ return await self._refresh_jwks_key(kid)
+
+ async def _refresh_jwks_key(self, kid: str | None) -> str:
+ """Refresh the complete key set while holding the refresh lock."""
# Fetch JWKS β€” with SSRF protection when enabled (untrusted URIs)
try:
jwks_data = await self._fetch_jwks()
@@ -367,7 +403,7 @@ class JWTVerifier(TokenVerifier):
# key published by the authorization server would reject every
# token, including ones signed by supported keys in the same set
# (#4515).
- self._jwks_cache = {}
+ keys: dict[str, str] = {}
skipped_kids: set[str] = set()
expected_key_type = _key_type_for_algorithm(self.algorithm)
for key_data in jwks_data.get("keys", []):
@@ -395,12 +431,13 @@ class JWTVerifier(TokenVerifier):
continue
if key_kid:
- self._jwks_cache[key_kid] = public_key
+ keys[key_kid] = public_key
else:
# Key without kid - use a default identifier
- self._jwks_cache["_default"] = public_key
+ keys["_default"] = public_key
- self._jwks_cache_time = current_time
+ self._jwks_cache = keys
+ self._jwks_cache_time = time.monotonic()
# Select the appropriate key
if kid:
diff --git a/tests/server/auth/test_jwks_refresh.py b/tests/server/auth/test_jwks_refresh.py
new file mode 100644
index 000000000..f8fb605a8
--- /dev/null
+++ b/tests/server/auth/test_jwks_refresh.py
@@ -0,0 +1,224 @@
+"""JWKS lookups share refreshes while keeping cached keys available."""
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import httpx2
+import pytest
+from joserfc import jwk
+
+from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair
+
+
+def key_data(rsa_key_pair: RSAKeyPair) -> dict[str, Any]:
+ return {
+ **jwk.import_key(rsa_key_pair.public_key, "RSA").as_dict(),
+ "kid": "current",
+ }
+
+
+def clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
+ values = [100.0]
+ monkeypatch.setattr(
+ "fastmcp.server.auth.providers.jwt.time",
+ SimpleNamespace(time=lambda: values[0], monotonic=lambda: values[0]),
+ )
+ return values
+
+
+async def test_distinct_unknown_ids_share_recent_refresh(key_data: dict[str, Any]):
+ requests: list[httpx2.Request] = []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(200, json={"keys": [key_data]})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ original = await verifier._get_jwks_key("current")
+ for index in range(8):
+ with pytest.raises(ValueError):
+ await verifier._get_jwks_key(f"other-{index}")
+ assert await verifier._get_jwks_key("current") == original
+ assert len(requests) == 1
+
+
+async def test_parallel_initial_lookups_share_one_refresh(key_data: dict[str, Any]):
+ requests: list[httpx2.Request] = []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ await asyncio.sleep(0)
+ return httpx2.Response(200, json={"keys": [key_data]})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ keys = await asyncio.gather(
+ *(verifier._get_jwks_key("current") for _ in range(8))
+ )
+ assert len(set(keys)) == 1
+ assert len(requests) == 1
+
+
+async def test_rotated_key_resolves_after_refresh_interval(
+ key_data: dict[str, Any], clock: list[float]
+):
+ documents = [{"keys": [key_data]}, {"keys": [{**key_data, "kid": "next"}]}]
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ return httpx2.Response(200, json=documents.pop(0))
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ await verifier._get_jwks_key("current")
+ clock[0] += 31
+ assert await verifier._get_jwks_key("next")
+ assert documents == []
+
+
+async def test_failed_refresh_is_shared_and_keeps_fresh_keys(
+ key_data: dict[str, Any], clock: list[float]
+):
+ requests: list[httpx2.Request] = []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ if len(requests) == 1:
+ return httpx2.Response(200, json={"keys": [key_data]})
+ return httpx2.Response(503)
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ original = await verifier._get_jwks_key("current")
+ clock[0] += 31
+ for index in range(8):
+ with pytest.raises(ValueError):
+ await verifier._get_jwks_key(f"other-{index}")
+ assert await verifier._get_jwks_key("current") == original
+ assert len(requests) == 2
+
+
[email protected]("keys_present", [False, True])
+async def test_no_id_lookup_shares_recent_refresh(
+ key_data: dict[str, Any], keys_present: bool
+):
+ requests: list[httpx2.Request] = []
+ keys = [key_data, {**key_data, "kid": "second"}] if keys_present else []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(200, json={"keys": keys})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ for _ in range(3):
+ with pytest.raises(ValueError):
+ await verifier._get_jwks_key(None)
+ assert len(requests) == 1
+
+
+async def test_zero_interval_allows_immediate_rotation(key_data: dict[str, Any]):
+ documents = [{"keys": [key_data]}, {"keys": [{**key_data, "kid": "next"}]}]
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ return httpx2.Response(200, json=documents.pop(0))
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys",
+ http_client=client,
+ jwks_refresh_interval=0,
+ )
+ await verifier._get_jwks_key("current")
+ assert await verifier._get_jwks_key("next")
+ assert documents == []
+
+
[email protected]("interval", [-1, float("inf"), float("nan")])
+def test_refresh_interval_requires_finite_nonnegative_value(interval: float):
+ with pytest.raises(ValueError, match="jwks_refresh_interval"):
+ JWTVerifier(
+ jwks_uri="https://issuer.example/keys", jwks_refresh_interval=interval
+ )
+
+
+async def test_signature_rejections_leave_cached_key_available(
+ key_data: dict[str, Any], rsa_key_pair: RSAKeyPair
+):
+ requests: list[httpx2.Request] = []
+ other = RSAKeyPair.generate()
+ good = rsa_key_pair.create_token(subject="reader", kid="current")
+ bad = other.create_token(subject="reader", kid="current")
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(200, json={"keys": [key_data]})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ assert await verifier.load_access_token(good) is not None
+ for _ in range(3):
+ assert await verifier.load_access_token(bad) is None
+ assert await verifier.load_access_token(good) is not None
+ assert len(requests) == 1
+
+
+async def test_expired_keys_wait_for_successful_refresh(
+ key_data: dict[str, Any], clock: list[float]
+):
+ requests: list[httpx2.Request] = []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(200, json={"keys": [key_data]})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ original = await verifier._get_jwks_key("current")
+ clock[0] += 3601
+ assert await verifier._get_jwks_key("current") == original
+ assert len(requests) == 2
+
+
+async def test_failed_refresh_does_not_reuse_expired_keys(
+ key_data: dict[str, Any], clock: list[float]
+):
+ requests: list[httpx2.Request] = []
+
+ async def respond(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ if len(requests) == 2:
+ return httpx2.Response(503)
+ return httpx2.Response(200, json={"keys": [key_data]})
+
+ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client:
+ verifier = JWTVerifier(
+ jwks_uri="https://issuer.example/keys", http_client=client
+ )
+ original = await verifier._get_jwks_key("current")
+ clock[0] += 3601
+ with pytest.raises(ValueError):
+ await verifier._get_jwks_key("current")
+ with pytest.raises(ValueError):
+ await verifier._get_jwks_key("current")
+ assert len(requests) == 2
+ clock[0] += 31
+ assert await verifier._get_jwks_key("current") == original
+ assert len(requests) == 3