Middleware Configuration
This section covers advanced configuration options for Auth Middleware, including environment variables, custom providers, and performance tuning.
Basic Middleware Setup
The Auth Middleware is added to your FastAPI or Starlette application using the standard middleware protocol:
from fastapi import FastAPI
from auth_middleware import JwtAuthMiddleware
from auth_middleware.providers.oidc.oidc_provider import OidcProvider
app = FastAPI()
# Add authentication middleware
app.add_middleware(
JwtAuthMiddleware,
auth_provider=your_auth_provider,
# Additional configuration options...
)
Middleware Parameters
The JwtAuthMiddleware accepts the following parameters:
Parameter |
Description |
Type |
Default |
|---|---|---|---|
|
The authentication provider instance |
|
Required |
|
Accept |
|
|
|
Only authenticate paths equal to the prefix or below it; other paths skip the middleware and get no
|
|
|
|
|
|
|
Identity provider outages
If the JWKS or discovery endpoint cannot be reached (or answers nonsense), the middleware answers 503 with
Retry-After instead of 401: valid users are not told their credentials are wrong. While keys are already cached
they keep being served (with a 30 s retry back-off), so a short outage is invisible. Custom error_responder callables
receive AuthFailure(reason="unavailable"). Call await provider.aclose() on shutdown to cancel the background
JWKS refresh task.
A signed token that the library cannot turn into a user (no sub, over-long or malformed claims) is a 401.
Public and protected paths
JwtAuthMiddleware does not reject requests that carry no credentials: it sets
request.state.current_user to None and lets the request through, and an invalid token is answered with
401. Which routes require a user is decided by the guards (require_user(), require_authenticated(),
require_groups(...), require_permission(...)), so a public route is simply a route without a guard.
Authenticating only a subtree
Use path_prefix when several applications are mounted in one process and each has its own middleware (for
example a different audience per subtree). Paths equal to the prefix or below it are validated; every other path
skips the middleware entirely and gets no current_user:
app.add_middleware(
JwtAuthMiddleware,
auth_provider=studio_provider,
path_prefix="/api/studio/v1",
)
Environment Variables
Core Configuration
Environment Variable |
Description |
Default |
|---|---|---|
|
Disable all authentication |
|
|
Logging level |
|
|
Logger name |
|
Provider-Specific Variables
AWS Cognito:
AWS_COGNITO_USER_POOL_ID=us-east-1_abcdef123
AWS_COGNITO_USER_POOL_REGION=us-east-1
TOKEN_VERIFICATION_DISABLED=false
Azure Entra ID:
AZURE_TENANT_ID=your-tenant-id
AZURE_CLIENT_ID=your-client-id
AZURE_CLIENT_SECRET=your-client-secret
JWT Provider:
JWT_SECRET_KEY=your-secret-key
JWT_ALGORITHM=HS256
JWT_ISSUER=your-issuer
Custom Authentication Providers
Creating a Custom Provider
You can create custom authentication providers by implementing the AuthProvider interface:
from abc import ABC, abstractmethod
from typing import Optional
from auth_middleware.types import User
class CustomAuthProvider(ABC):
@abstractmethod
async def authenticate(self, token: str) -> Optional[User]:
"""Validate token and return user information."""
pass
@abstractmethod
async def get_user_groups(self, user: User) -> List[str]:
"""Get user group memberships."""
pass
Example Custom Provider
import jwt
from auth_middleware.types import User
from auth_middleware.exceptions import AuthenticationError
class ApiKeyProvider:
def __init__(self, valid_api_keys: dict):
self.valid_api_keys = valid_api_keys
async def authenticate(self, token: str) -> Optional[User]:
# Remove 'Bearer ' prefix if present
if token.startswith('Bearer '):
token = token[7:]
# Look up API key
user_info = self.valid_api_keys.get(token)
if not user_info:
raise AuthenticationError("Invalid API key")
return User(
id=user_info["id"],
name=user_info["name"],
email=user_info["email"],
groups=user_info.get("groups", []),
raw_token=token,
)
async def get_user_groups(self, user: User) -> List[str]:
return user.groups
# Usage
api_keys = {
"api_key_123": {
"id": "user1",
"name": "John Doe",
"email": "john@example.com",
"groups": ["user", "admin"]
}
}
app.add_middleware(
JwtAuthMiddleware,
auth_provider=ApiKeyProvider(api_keys)
)
Performance Configuration
Connection Pooling
For providers that make HTTP requests (like any OIDC-based provider), configure connection pooling:
import httpx
from auth_middleware.providers.oidc.oidc_provider import OidcProvider
# Custom HTTP client with connection pooling
http_client = httpx.AsyncClient(
timeout=30.0,
limits=httpx.Limits(
max_keepalive_connections=10,
max_connections=100,
)
)
# Note: This is conceptual - actual implementation may vary
auth_provider = OidcProvider(
settings=auth_settings,
http_client=http_client,
)
Caching Configuration
JWKS lookups are cached automatically — see JWKS Cache Strategies for the real,
supported configuration (jwks_cache_strategy, jwks_cache_interval,
jwks_cache_usages, background refresh).
Logging Configuration
Detailed Logging
Enable detailed logging for debugging:
import logging
# Configure auth middleware logging
auth_logger = logging.getLogger("auth_middleware")
auth_logger.setLevel(logging.DEBUG)
# Add handler
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
auth_logger.addHandler(handler)
Environment-based Logging
# Set log level via environment
AUTH_MIDDLEWARE_LOG_LEVEL=DEBUG
AUTH_MIDDLEWARE_LOG_FORMAT="%(asctime)s %(name)s %(levelname)s %(message)s"
AUTH_MIDDLEWARE_LOGGER_NAME="my_auth"
Security Best Practices
Token Security
Use HTTPS: Always use HTTPS in production to protect tokens in transit
Token Expiration: Ensure tokens have reasonable expiration times
Secure Storage: Never log or store JWT tokens in plain text
Rotation: Implement token rotation strategies
Configuration Security
Environment Variables: Store sensitive configuration in environment variables
Secrets Management: Use proper secrets management systems in production
Least Privilege: Configure minimal required permissions
Monitoring: Monitor authentication failures and suspicious activity
Error Handling Configuration
Custom Error Handlers
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from auth_middleware.exceptions import (
AuthenticationError,
InvalidTokenException,
)
app = FastAPI()
@app.exception_handler(AuthenticationError)
async def authentication_error_handler(request, exc):
return JSONResponse(
status_code=401,
content={
"error": "Authentication Failed",
"message": "Please provide a valid authentication token",
"type": "authentication_error"
}
)
@app.exception_handler(InvalidTokenException)
async def invalid_token_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={
"error": "Token Error",
"message": exc.detail,
"type": "invalid_token"
}
)
Development Configuration
Development Mode
For development and testing environments:
import os
# Development-friendly configuration
auth_settings = OidcProviderSettings(
issuer=os.getenv("OIDC_ISSUER"),
audience=os.getenv("OIDC_AUDIENCE"),
jwt_token_verification_disabled=os.getenv("ENVIRONMENT") == "development",
)
Hot Reloading
Auth Middleware works with FastAPI’s hot reloading in development:
# Development server with hot reloading
uvicorn main:app --reload --host 0.0.0.0 --port 8000
Testing Configuration
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def test_app():
app = FastAPI()
# Use mock auth provider for testing
app.add_middleware(
JwtAuthMiddleware,
auth_provider=MockAuthProvider(),
)
return app
def test_protected_endpoint(test_app):
client = TestClient(test_app)
response = client.get(
"/protected",
headers={"Authorization": "Bearer test_token"}
)
assert response.status_code == 200
For more specific provider configurations, see the individual provider documentation:
- Generic OIDC Provider
AUTH_MIDDLEWARE_JWKS_CACHE_INTERVAL_MINUTES
JWKS keys file refreshing interval
An integer value
20
AUTH_MIDDLEWARE_JWKS_CACHE_USAGES
JWKS keys refreshing interval (counter)
An integer value
1000