Search Topics
Search across all FastAPI topics
Auth & Security
3 topicsSecure your API endpoints with authentication and authorization. From simple API keys to full OAuth2 flows with JWT tokens.
Tip
FastAPI has built-in support for OAuth2 with Password flow and Bearer tokens. The security utilities integrate with the automatic OpenAPI documentation, so your /docs page gets a working "Authorize" button.
How JWT Authentication Works
Step 1: Send Credentials
The client sends a username and password to the /token endpoint.
Try It: JWT Decoder
These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.
SECRET_KEY = "my-super-secret-key" # Hardcoded!
ALGORITHM = "HS256"
def create_token(data: dict):
return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)def create_access_token(data: dict):
to_encode = data.copy()
# No expiry!
return jwt.encode(to_encode, SECRET_KEY)