Quick Start
The JWT middleware provides two main features:- Token Validation: Validates JWT tokens and handles authentication
- Parameter Injection: Automatically injects user_id, session_id, and custom claims into endpoint parameters
Configuration Options
Parameter | Description | Default |
---|---|---|
secret_key | Secret key for JWT verification | Optional, will use JWT_SECRET_KEY environment variable if not provided |
algorithm | JWT algorithm (HS256, RS256, etc.) | ”HS256” |
token_source | Where to extract token from. HEADER , COOKIE , or BOTH . | TokenSource.HEADER |
token_header_key | Key to use for the Authorization header (only used when token_source is HEADER or BOTH ) | “Authorization” |
cookie_name | Cookie name when using cookies (only used when token_source is COOKIE or BOTH ) | “access_token” |
validate | Enable token validation | True |
excluded_route_paths | Routes to skip middleware (useful for health checks, etc.) | [] |
scopes_claim | JWT claim for scopes | None |
user_id_claim | JWT claim for user ID | ”sub” |
session_id_claim | JWT claim for session ID | ”session_id” |
dependencies_claims | List of additional claims to extract for dependencies parameter | [] |
session_state_claims | List of additional claims to extract for session_state parameter | [] |
Token Sources
The middleware supports three token sources:Extract JWT from
Authorization: Bearer <token>
header.Parameter Injection
The middleware automatically injects JWT claims into the request object flowing across your FastAPI state. This is a great way to resolve data from your token into parameters received by your endpoints. These are the parameters automatically injected by our JWT middleware into your endpoints:user_id
session_id
dependencies
session_state
For example, in/agents/{agent_id}/runs
, theuser_id
,session_id
,dependencies
andsession_state
are automatically used if they were extracted from the JWT token.
- Automatically using the
user_id
andsession_id
from your JWT token when running an agent - Automatically filtering sessions retrieved from
/sessions
endpoints byuser_id
(where applicable) - Automatically injecting
dependencies
from claims in your JWT token into the agent run, which then is available on tools called by your agent
Security Features
Remember to always use strong secret keys, don’t hardcode them anywhere in your code and enable validation in production.
validate=True
, the middleware:
- Verifies JWT signature using the secret key
- Checks token expiration (
exp
claim) - Returns 401 errors for invalid/expired tokens
HTTP-Only Cookies: When using cookies:
- Set
httponly=True
to prevent JavaScript access (XSS protection) - Set
secure=True
for HTTPS-only transmission - Set
samesite="strict"
for CSRF protection