AuthMiddleware to your own FastAPI app, then pass the app to AgentOS as base_app. The middleware covers your routes and the AgentOS routes.
AuthMiddleware was named JWTMiddleware before v2.7. JWTMiddleware still works as an alias.Code
custom_fastapi_jwt.py
Usage
1
Set up your virtual environment
2
Set Environment Variables
3
Install dependencies
4
Setup PostgreSQL Database
5
Run Example
6
Test Authentication Flow
Step 1: Login to get JWT tokenStep 2: Test protected endpoints with tokenStep 3: Test without token (should get 401)
7
Test on a browser
- Visit the API docs: http://localhost:7777/docs
- Login via form: Try the
/auth/loginendpoint withusername=demoandpassword=password - Copy the token: From the response, copy the
access_tokenvalue - Authorize in docs: Click the “Authorize” button and paste the token. Swagger adds the
Bearerprefix for you. - Test protected endpoints: Try any AgentOS endpoint - they should now work
Authentication Flow
1
User Login
Client sends credentials to
/auth/login:2
Token Generation
Server validates credentials and returns JWT:
3
Authenticated Requests
Client includes token in Authorization header:
4
Middleware Validation
The auth middleware validates the token and allows or denies access