Skip to main content

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:

  1. The middleware checks whether the request path is configured as a bypass path.
  2. It reads the Authorization header and expects the format: Authorization: Bearer <ACCESS_TOKEN>.
  3. The access token is validated by calling AWS Cognito cognito-idp.get_user.
  4. If the token is valid, the authenticated user data is attached to the request object.
  5. 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_user responses 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.

Metadata

Release files for django-cognito-auth-middleware 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-cognito-auth-middleware 0.1.1
File Size Uploaded Provenance
django_cognito_auth_middleware-0.1.1.tar.gz 5.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-cognito-auth-middleware 0.1.1
File Interpreter ABI Platform
django_cognito_auth_middleware-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 11.5 kB

Release files / django_cognito_auth_middleware-0.1.1.tar.gz

Download URL django_cognito_auth_middleware-0.1.1.tar.gz
Size 5.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f2dbc13e02a763c75e44254abccfbe1fa22bc2d0403f0e4969bdd01154466630
BLAKE2b-256 checksum
How to use checksums
d892f702f5d5a1695620f0cb4ee82e4cc8eecf69465cb1d587d062aab7e35505
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / django_cognito_auth_middleware-0.1.1-py3-none-any.whl

Download URL django_cognito_auth_middleware-0.1.1-py3-none-any.whl
Size 6.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93aa7a6a091fb86aa26fcb7b5fc3ee15b7e6dce373bc0900b77216c385cd33e7
BLAKE2b-256 checksum
How to use checksums
c96ed4585e2077f93160f450846038917354b3753c8c867403f8c1f66f96bf83
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Security for django-cognito-auth-middleware 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page