API Reference
This section provides comprehensive API documentation for all components of the auth-middleware library.
Core Components
Authentication Providers
The library supports multiple authentication providers for different identity systems:
Utilities
Additional utilities and helper components:
Quick Reference
Common Classes and Functions
- Middleware
auth_middleware.JwtAuthMiddleware
- Main authentication middleware
- Authentication Functions
auth_middleware.require_user()
- Require authenticated userauth_middleware.require_groups()
- Require group membershipauth_middleware.require_permissions()
- Require specific permissionsauth_middleware.get_current_user()
- Get current user from request
- Providers
auth_middleware.providers.authn.cognito_provider.CognitoProvider
- AWS Cognitoauth_middleware.providers.authn.entra_id_provider.EntraIdProvider
- Azure Entra IDauth_middleware.providers.authn.jwt_provider.JWTProvider
- Generic JWT
- Exceptions
auth_middleware.exceptions.AuthenticationError
- Authentication failuresauth_middleware.exceptions.AuthorizationError
- Authorization failuresauth_middleware.exceptions.ConfigurationError
- Configuration issues
- Types
auth_middleware.types.User
- User representationauth_middleware.types.AuthenticatedRequest
- Extended request with auth context
Usage Patterns
Basic Setup
from fastapi import FastAPI
from auth_middleware import JwtAuthMiddleware
from auth_middleware.providers.authn.cognito_provider import CognitoProvider
app = FastAPI()
# Setup authentication
auth_provider = CognitoProvider(
user_pool_id="your-user-pool-id",
client_id="your-client-id",
region="us-east-1"
)
app.add_middleware(JwtAuthMiddleware, auth_provider=auth_provider)
Endpoint Protection
from fastapi import Depends
from auth_middleware import require_user, require_groups
@app.get("/protected", dependencies=[Depends(require_user())])
async def protected_endpoint(request):
user = request.state.current_user
return {"message": f"Hello {user.name}"}
@app.get("/admin", dependencies=[Depends(require_groups(["administrators"]))])
async def admin_endpoint(request):
return {"message": "Admin access granted"}
Error Handling
from fastapi.responses import JSONResponse
from auth_middleware.exceptions import AuthenticationError, AuthorizationError
@app.exception_handler(AuthenticationError)
async def auth_error_handler(request, exc):
return JSONResponse(
status_code=401,
content={"error": "Authentication failed"}
)
@app.exception_handler(AuthorizationError)
async def authz_error_handler(request, exc):
return JSONResponse(
status_code=403,
content={"error": "Access denied"}
)