Reusable Django middleware for AWS Cognito authentication
Project description
Django Cognito Auth Middleware
A reusable Django middleware that authenticates API requests using AWS Cognito
Access Tokens. It validates incoming requests by calling
cognito-idp.get_user, attaches authenticated user data to the request, and
optionally caches Cognito responses to reduce repeated network calls.
This package is designed to be plug-and-play, production-safe, and reusable across multiple Django projects.
Features
- Verifies AWS Cognito Access Tokens
- Protects all API endpoints by default
- Supports public (bypass) paths
- Optional short-lived caching using Django cache backends
- Attaches Cognito user data directly to the request object
- Works with both Django and Django REST Framework
- Clean, minimal, and reusable design
Installation
pip install django-cognito-auth-middleware
Basic Usage
Add the middleware to your Django project’s settings.py:
MIDDLEWARE = [
# ...
"django_cognito_auth.middleware.CognitoAuthMiddleware",
]
Once added, all incoming requests will be authenticated using AWS Cognito unless explicitly bypassed.
How It Works
For every incoming HTTP request:
- The middleware checks whether the request path is configured as a bypass path.
- It reads the
Authorizationheader and expects the format:Authorization: Bearer <ACCESS_TOKEN>. - The access token is validated by calling AWS Cognito
cognito-idp.get_user. - If the token is valid, the authenticated user data is attached to the request object.
- If the token is missing, invalid, or expired, the middleware immediately returns an HTTP 401 response.
Request Attributes
After successful authentication, the following attributes are available on the request object:
request.cognito_user # Cognito username (string)
request.cognito_attributes # Dict of Cognito user attributes
request.cognito_token # Raw access token
These can be accessed in Django views, DRF views, serializers, permissions, or business logic.
Configuration Options
All configuration is optional and controlled via settings.py.
Cognito Region
COGNITO_REGION = "ap-south-1"
If not provided, the middleware falls back to AWS_REGION.
If neither is set, it defaults to ap-south-1.
Bypass Paths (Public Endpoints)
COGNITO_BYPASS_PATHS = [
"/health/",
"/login/",
"/public/",
]
Requests whose paths match any entry in this list will skip Cognito authentication.
Cognito Response Caching
COGNITO_GET_USER_CACHE_SECONDS = 60
When enabled:
- Cognito
get_userresponses are cached using Django’s cache framework - Cache keys are derived from a secure SHA-256 hash of the access token
- This significantly reduces repeated calls to AWS Cognito
Set to 0 (default) to disable caching.
Error Handling
If authentication fails, the middleware returns an HTTP 401 response:
{
"detail": "Invalid or expired access token"
}
No view or business logic is executed for unauthorized requests.
Example Usage in a View
from django.http import JsonResponse
def my_view(request):
username = request.cognito_user
tenant_id = request.cognito_attributes.get("custom:tenant_id")
profile = request.cognito_attributes.get("profile")
return JsonResponse({
"user": username,
"tenant_id": tenant_id,
"profile": profile,
})
Compatible Cache Backends
The middleware works with any Django-supported cache backend, including:
- Redis
- Memcached
- Local memory cache
- Database cache
Security Notes
- This middleware validates Cognito Access Tokens by calling AWS Cognito
- Tokens are never logged or stored in plaintext
- Cached tokens are stored using a secure hash
- HTTPS is strongly recommended in production
License
This project is licensed under the MIT License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_cognito_auth_middleware-0.1.1.tar.gz.
File metadata
- Download URL: django_cognito_auth_middleware-0.1.1.tar.gz
- Upload date:
- Size: 5.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f2dbc13e02a763c75e44254abccfbe1fa22bc2d0403f0e4969bdd01154466630
|
|
| MD5 |
2b645632c1685a3f7b9d36e0fd0032a6
|
|
| BLAKE2b-256 |
d892f702f5d5a1695620f0cb4ee82e4cc8eecf69465cb1d587d062aab7e35505
|
File details
Details for the file django_cognito_auth_middleware-0.1.1-py3-none-any.whl.
File metadata
- Download URL: django_cognito_auth_middleware-0.1.1-py3-none-any.whl
- Upload date:
- Size: 6.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
93aa7a6a091fb86aa26fcb7b5fc3ee15b7e6dce373bc0900b77216c385cd33e7
|
|
| MD5 |
b80138181411e850da7a421083f2cff9
|
|
| BLAKE2b-256 |
c96ed4585e2077f93160f450846038917354b3753c8c867403f8c1f66f96bf83
|