> ## Documentation Index
> Fetch the complete documentation index at: https://agno-v2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# AgentOS Middleware

> Add authentication, logging, monitoring, and security features to your AgentOS application using middleware

v2.1.0 (Introduced in v2.1.0)

AgentOS is built on FastAPI, so you can add any [FastAPI/Starlette-compatible middleware](https://fastapi.tiangolo.com/tutorial/middleware/) for authentication, logging, monitoring, and security.

Agno ships with a built-in auth middleware (`AuthMiddleware`) that handles JWTs, service-account tokens, and the OS security key. You can write your own custom middleware for rate limiting, request logging, and security headers.

See the following guides:

> [card] [Custom Middleware](https://agno-v2.mintlify.site/agent-os/middleware/custom.md)
>
> Create your own middleware for logging, rate limiting, monitoring, and security.

> [card] [JWT Middleware](https://agno-v2.mintlify.site/agent-os/middleware/jwt.md)
>
> Built-in JWT authentication with automatic parameter injection and claims extraction.

> [card] [Authorization](https://agno-v2.mintlify.site/agent-os/security/authorization/overview.md)
>
> JWT validation with role-based access control and fine-grained permission scopes.

## Quick Start

Add middleware to the FastAPI app returned by `get_app()`:

```python agent_os.py theme={null}
from agno.os import AgentOS
from agno.os.middleware.jwt import AuthMiddleware
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIResponses
from agno.agent import Agent

db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")

agent = Agent(
    name="Basic Agent",
    model=OpenAIResponses(id="gpt-5.2"),
    db=db,
)

# Create your AgentOS app
agent_os = AgentOS(agents=[agent])
app = agent_os.get_app()

# Add middleware
app.add_middleware(
    AuthMiddleware,
    verification_keys=["your-jwt-verification-key"],
    validate=True
)

if __name__ == "__main__":
    agent_os.serve(app="agent_os:app", reload=True)
```

> [!NOTE]
>
> Test middleware thoroughly in your own staging environment before production deployment.

> [!TIP]
>
> **Performance Impact:** Each middleware layer adds latency to requests.

## Common Use Cases

> [tab] Authentication
>
> **Secure your AgentOS with JWT authentication:**
>
> * Extract tokens from headers or cookies
> * Automatic parameter injection (user\_id, session\_id)
> * Custom claims extraction for `dependencies` and `session_state`
> * Route exclusion for public endpoints
>
> [Learn more about JWT Middleware](https://agno-v2.mintlify.site/agent-os/middleware/jwt.md)

> [tab] RBAC Authorization
>
> **Control access with permission scopes:**
>
> * Validate JWT scopes against required permissions
> * Per-resource access control (specific agents/teams/workflows)
> * Admin scope for full access
> * Customizable scope mappings
>
> [Authorization](https://agno-v2.mintlify.site/agent-os/security/authorization/overview.md)

> [tab] Rate Limiting
>
> **Prevent API abuse with rate limiting:**
>
> ```python theme={null}
> class RateLimitMiddleware(BaseHTTPMiddleware):
>     def __init__(self, app, requests_per_minute: int = 60):
>         super().__init__(app)
>         self.requests_per_minute = requests_per_minute
>         # ... implementation
>
> app.add_middleware(RateLimitMiddleware, requests_per_minute=100)
> ```

> [tab] Logging
>
> **Monitor requests and responses:**
>
> ```python theme={null}
> class LoggingMiddleware(BaseHTTPMiddleware):
>     async def dispatch(self, request: Request, call_next):
>         start_time = time.time()
>         response = await call_next(request)
>         process_time = time.time() - start_time
>         # Log request details...
>         return response
> ```

See [Custom Middleware](https://agno-v2.mintlify.site/agent-os/usage/middleware/custom-middleware.md) for complete rate-limiting and request-logging implementations.

## Middleware Execution Order

> [!WARNING]
>
> Middleware is executed in reverse order of addition. The last middleware added runs first.

```python theme={null}
app.add_middleware(MiddlewareA)  # Runs third (closest to route)
app.add_middleware(MiddlewareB)  # Runs second
app.add_middleware(MiddlewareC)  # Runs first (outermost)

# Request: C -> B -> A -> Your Route
# Response: Your Route -> A -> B -> C
```

**Best Practice:** Aim for this execution order. Since the last middleware added runs first, add them in reverse:

1. **Security middleware** (CORS, security headers)
2. **Authentication middleware** (JWT, session validation)
3. **Monitoring middleware** (logging, metrics)
4. **Business logic middleware** (rate limiting, custom logic)

## Developer Resources

### Examples

> [card] [JWT with Headers](https://agno-v2.mintlify.site/agent-os/usage/middleware/jwt-middleware.md)
>
> JWT authentication using Authorization headers for API clients.

> [card] [JWT with Cookies](https://agno-v2.mintlify.site/agent-os/usage/middleware/jwt-cookies.md)
>
> JWT authentication using HTTP-only cookies for web applications.

> [card] [Custom Middleware](https://agno-v2.mintlify.site/agent-os/usage/middleware/custom-middleware.md)
>
> Rate limiting and request logging middleware implementation.

> [card] [Custom FastAPI + JWT](https://agno-v2.mintlify.site/agent-os/usage/middleware/custom-fastapi-jwt.md)
>
> Custom FastAPI app with JWT middleware and AgentOS integration.

> [card] [Authorization](https://agno-v2.mintlify.site/agent-os/security/authorization/overview.md)
>
> Scopes, roles, and access control.

### External Resources

> [card] [FastAPI Middleware](https://fastapi.tiangolo.com/tutorial/middleware/)
>
> Official FastAPI middleware documentation and examples.

> [card] [Starlette Middleware](https://www.starlette.io/middleware/)
>
> Starlette middleware reference and implementation guides.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.