Search Topics

Search across all FastAPI topics

GitHub

Auth & Security

3 topics

Secure 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.

1
Storing secrets in code
Hardcoding JWT secrets and API keys in source files
Don't do this
auth.py
SECRET_KEY = "my-super-secret-key"  # Hardcoded!
ALGORITHM = "HS256"

def create_token(data: dict):
    return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
Never hardcode secrets in source files. Use environment variables or a .env file with pydantic-settings to manage configuration securely.
2
Not validating token expiry
Creating tokens without expiration timestamps
Don't do this
auth.py
def create_access_token(data: dict):
    to_encode = data.copy()
    # No expiry!
    return jwt.encode(to_encode, SECRET_KEY)
Always set an expiration time on JWT tokens. Without expiry, a leaked token grants permanent access. Use short-lived access tokens with refresh tokens for better security.