Skip to main content
AuthMiddleware is the AgentOS authentication layer. It validates JWTs, service-account tokens (agno_pat_...), and the OS security key. For JWTs it extracts tokens from Authorization headers or cookies, validates them, and injects user_id, session_id, and custom claims into your endpoints. This page covers the JWT configuration. For the other two credential types, see Service Accounts and the security key.
The class was renamed from JWTMiddleware in v2.7. JWTMiddleware remains as an alias, so existing app.add_middleware(JWTMiddleware, ...) setups keep working.
The middleware provides three main features:
  1. Token Validation: Validates JWT tokens and handles authentication
  2. Parameter Injection: Automatically injects user_id, session_id, and custom claims into endpoint parameters
  3. RBAC Authorization: Validates scopes against required permissions for each endpoint
auth_middleware_setup.py

Coverage Across Surfaces

AgentOS installs a single AuthMiddleware instance on the parent app in every authenticated deployment mode. A token accepted on one surface is accepted with identical constraints on the others.

Credential Dispatch

The middleware resolves each bearer credential in order:
  1. Tokens with the agno_pat_ prefix authenticate as service accounts against the AgentOS database. This happens before JWT validation. Service-account scopes are enforced even when authorization=False, since they are ACL data owned by your AgentOS instance.
  2. The internal service token, used by the scheduler executor to run scheduled jobs.
  3. The OS security key, when no JWT source is configured.
  4. Anything else is validated as a JWT.

Token Sources

The middleware supports three token sources:
Extract JWT from Authorization: Bearer <token> header.

JWKS File Support

For environments using RSA keys managed via JWKS (JSON Web Key Set), you can point to a static JWKS file instead of providing raw public keys:
jwks_file_setup.py
The middleware will:
  1. Load public keys from the JWKS file at startup
  2. Match incoming tokens by their kid (key ID) header claim
  3. Validate signatures using the appropriate key

JWKS File Format

The JWKS file should follow the standard format:

Environment Variable

You can also set the JWKS file path via environment variable:
JWKS keys are tried first (matched by kid). If no matching key is found, the middleware falls back to verification_keys if provided.

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 claims
  • session_id - Session identifier from token claims
  • dependencies - Custom claims for agent tools
  • session_state - Custom claims for session management
For example, the /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_id and session_id from your JWT token when running an agent
  • Automatically filtering sessions retrieved from /sessions endpoints by user_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
See the full example.

Security Features

Use strong verification keys, store them securely (not in code), and enable validation in production.
Token Validation: When validate=True, the middleware:
  • Verifies JWT signature using the verification key
  • Checks token expiration (exp claim)
  • Returns 401 errors for invalid/expired tokens
Audience Verification: When verify_audience=True, the middleware:
  • If audience is provided, it will validate the token’s audience claim matches the expected audience claim
  • If audience is not provided, it will validate the token’s audience claim matches the AgentOS ID
  • Optionally set the audience_claim to validate a custom audience claim
  • Returns 401 for tokens with mismatched audience
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

Local Development

Do not use validate=False in production. The middleware decodes claims without verifying the JWT signature.
Skip signature verification in local development, or when an upstream API gateway already validates JWTs.
No verification key is required. Claims are extracted from the token but not authenticated.

RBAC Authorization

Enable Role-Based Access Control (RBAC) to validate JWT scopes against required permissions:
jwt_with_rbac.py
When authorization=True, the middleware:
  • Checks the scopes claim in JWT tokens
  • Validates scopes against required permissions for each endpoint
  • Returns 403 Forbidden for insufficient permissions

Scope Format

Custom Scope Mappings

Override or extend default scope mappings:
custom_scope_mappings.py
For all available scopes and default endpoint mappings, see Scopes.

User Isolation

RBAC controls which endpoints a caller can hit. User isolation controls which rows they can see and mutate. The two are independent toggles.
jwt_with_user_isolation.py
When user_isolation=True, non-admin callers are scoped to their own user_id (from the JWT sub claim) for sessions, memory, traces and approvals. Callers holding admin_scope bypass isolation. See Per-User Data Isolation for the full behavior.

Excluded Routes

These routes skip JWT and RBAC checks by default:
Override them with excluded_route_paths:
jwt_excluded_routes.py
excluded_route_paths replaces the defaults. Re-include any default routes you want to keep.

Configuration Options

See the AuthMiddleware reference for the complete list of configuration options.

Authentication Options

Constructing the middleware requires at least one credential source: a JWT key source (verification_keys, jwks_file, or their environment variables), validate=False, a security_key, or a service_account_verifier. authorization=True also requires a JWT source (verification keys, a JWKS file, or validate=False for unverified dev mode).

Token Source Options

Claim Extraction Options

Authorization Options (RBAC)

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.

Authorization

Scopes, roles, and access control configuration.

AuthMiddleware Reference

Complete auth middleware class reference.

External Resources

PyJWT Documentation

Official PyJWT library documentation for JWT encoding and decoding.