pycognito

2024.5.1 · active · verified Sat Apr 11

pycognito is a Python library that provides a simplified interface for interacting with AWS Cognito User Pools, wrapping Boto3's Cognito client. It includes built-in support for the Secure Remote Password (SRP) protocol, making user authentication straightforward. The current version is 2024.5.1, and it typically releases new versions monthly or bi-monthly, incorporating fixes and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Cognito` client and authenticate a user using their username and password. It automatically handles the SRP (Secure Remote Password) protocol. Ensure you replace the placeholder values for `USER_POOL_ID`, `CLIENT_ID`, `USERNAME`, and `PASSWORD` with your actual Cognito credentials, ideally loaded from environment variables.

import os
from pycognito import Cognito

# It's highly recommended to load these from environment variables or a secure configuration system.
# Replace 'your_pool_id', 'your_client_id', 'your_username', 'YourStrongPassword123!'
USER_POOL_ID = os.environ.get('COGNITO_USER_POOL_ID', 'us-east-1_your_pool_id')
CLIENT_ID = os.environ.get('COGNITO_CLIENT_ID', 'your_client_id')
USERNAME = os.environ.get('COGNITO_USERNAME', 'your_username')
PASSWORD = os.environ.get('COGNITO_PASSWORD', 'YourStrongPassword123!')

# Check if placeholder values are still present
if 'your_pool_id' in USER_POOL_ID or 'your_client_id' in CLIENT_ID or\
   USERNAME == 'your_username' or PASSWORD == 'YourStrongPassword123!':
    print("Please set COGNITO_USER_POOL_ID, COGNITO_CLIENT_ID, COGNITO_USERNAME, and COGNITO_PASSWORD environment variables or replace placeholders in the code.")
else:
    try:
        # Initialize Cognito with User Pool ID, Client ID, and username
        c = Cognito(USER_POOL_ID, CLIENT_ID, username=USERNAME)

        # Authenticate the user. SRP (Secure Remote Password) protocol is handled automatically.
        c.authenticate(password=PASSWORD)

        print(f"Successfully authenticated user: {USERNAME}")
        print(f"Access Token (first 30 chars): {c.access_token[:30]}...")
        print(f"ID Token (first 30 chars): {c.id_token[:30]}...")
        # Refresh token is also available as c.refresh_token
        
        # Example: Get user attributes
        user_attributes = c.get_user_attributes()
        print(f"User attributes: {user_attributes}")

    except Exception as e:
        print(f"Authentication failed: {e}")

view raw JSON →