-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
36 lines (27 loc) · 1.11 KB
/
decorators.py
File metadata and controls
36 lines (27 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import jwt
from functools import wraps
import os, time
from starlette.responses import JSONResponse
from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = JWTVerifier(
jwks_uri=os.environ.get("JWKS_ENDPOINT", ""),
issuer=os.environ.get("ISSUER_URL", "http://localhost:8000"),
algorithm=os.environ.get("JWT_ALGORITHM", "RS256")
)
def require_api_key(func):
""""
Decorator to require an API key for certain routes.
This is a check for a specific API key in the Authorization header and
makes sure the token is valid.
"""
@wraps(func)
async def wrapper(request, *args, **kwargs):
token = request.headers.get("Authorization", "")[7:] # Remove "Bearer " prefix
if not token:
return JSONResponse({"error": "Forbidden"}, status_code=403)
# Validate the token with the verifier
auth_info = await auth.verify_token(token)
if not auth_info:
return JSONResponse({"error": "Forbidden"}, status_code=403)
return await func(request, *args, **kwargs)
return wrapper