- Token Validation: Validates JWT tokens and handles authentication
- Parameter Injection: Automatically injects user_id, session_id, and custom claims into endpoint parameters
jwt_middleware_setup.py
Token Sources
The middleware supports three token sources:- Both Sources
Extract JWT from
Authorization: Bearer <token> header.Parameter Injection
The middleware automatically injects JWT claims into AgentOS endpoints. The following parameters are extracted from tokens and injected into requests:user_id- User identifier from token claimssession_id- Session identifier from token claimsdependencies- Custom claims for agent toolssession_state- Custom claims for session management
/agents/{agent_id}/runs endpoint automatically uses user_id, session_id, dependencies, and session_state from the JWT token when available.
This is useful for:
- Automatically using the
user_idandsession_idfrom your JWT token when running an agent - Automatically filtering sessions retrieved from
/sessionsendpoints byuser_id(where applicable) - Automatically injecting
dependenciesfrom claims in your JWT token into the agent run, which then is available on tools called by your agent
Security Features
Use strong secret keys, store them securely (not in code), and enable validation in production.
validate=True, the middleware:
- Verifies JWT signature using the secret key
- Checks token expiration (
expclaim) - Returns 401 errors for invalid/expired tokens
Excluded Routes
Skip middleware for specific routes:jwt_excluded_routes.py
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.) | None |
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 | [] |
Examples
JWT with Headers
JWT authentication using Authorization headers for API clients.
JWT with Cookies
JWT authentication using HTTP-only cookies for web applications.
Custom FastAPI + JWT
Custom FastAPI app with JWT middleware and AgentOS integration.