Securing Containerized Applications with AWS Cognito

March 5, 2025
AWS Cognito
Authentication
Django
Security
Containers

At Vectra AI, I built a Cognito-integrated user management API with Django REST Framework for authentication across containerized applications. This article shares the approach and implementation details.

Why AWS Cognito?

AWS Cognito provides a fully managed user directory service with:

  • User registration and sign-in
  • Multi-factor authentication
  • Social identity provider integration
  • Token-based authentication
  • Scalability and security

Architecture Overview

Our solution consisted of:

  • AWS Cognito User Pool for user management
  • Django REST API for business logic
  • JWT token validation middleware
  • Role-based access control

Setting Up AWS Cognito

First, create a User Pool in AWS Cognito with appropriate settings for password policies, MFA, and custom attributes.

Django REST Framework Integration

We created a custom authentication backend for Django that validates Cognito JWT tokens:

# authentication.py
import jwt
from django.conf import settings
from rest_framework import authentication, exceptions

ISSUER = (
    f"https://cognito-idp.{settings.COGNITO_REGION}.amazonaws.com/"
    f"{settings.COGNITO_USER_POOL_ID}"
)
jwks_client = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json")


class CognitoAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.headers.get("Authorization", "")
        if not auth_header.startswith("Bearer "):
            return None

        token = auth_header.removeprefix("Bearer ")

        try:
            # Verify the signature against the user pool's public keys,
            # along with the issuer, audience and expiry of an ID token
            signing_key = jwks_client.get_signing_key_from_jwt(token)
            payload = jwt.decode(
                token,
                signing_key.key,
                algorithms=["RS256"],
                issuer=ISSUER,
                audience=settings.COGNITO_APP_CLIENT_ID,
            )
        except jwt.PyJWTError:
            raise exceptions.AuthenticationFailed("Invalid token")

        # Get or create the user for this Cognito ID
        user = get_user_from_cognito_id(payload["sub"])
        return (user, token)

User Management API

Our API provided endpoints for:

  • User registration and confirmation
  • Authentication and token refresh
  • Password reset
  • User profile management
  • Role and permission assignment

Containerization

The API was containerized using Docker and deployed on AWS ECS, with environment variables for Cognito configuration.

Security Considerations

  • Verifying every token's signature, issuer, audience and expiry
  • HTTPS for all communications
  • Proper handling of refresh tokens
  • Rate limiting to prevent brute force attacks

Conclusion

Integrating AWS Cognito with Django REST Framework gives containerized applications a shared authentication service. It offloads the complexity of user management while maintaining flexibility for custom business logic.