or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mddevice-authentication.mdgroup-management.mdhttp-integration.mdindex.mdmfa.mdpassword-management.mdsrp-authentication.mduser-management.md
tile.json

tessl/pypi-pycognito

Python class to integrate Boto3's Cognito client so it is easy to login users with SRP support.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pycognito@2024.5.x

To install, run

npx @tessl/cli install tessl/pypi-pycognito@2024.5.0

index.mddocs/

pycognito

A comprehensive Python library for integrating with AWS Cognito authentication services, offering simplified user management operations including registration, authentication, password management, and token handling. It wraps Boto3's Cognito client with an easy-to-use interface that supports Secure Remote Password (SRP) authentication protocol, making it ideal for serverless applications and web services that require AWS Cognito user pool integration.

Package Information

  • Package Name: pycognito
  • Language: Python
  • Installation: pip install pycognito

Core Imports

from pycognito import Cognito

Import specific utilities:

from pycognito import UserObj, GroupObj
from pycognito.aws_srp import AWSSRP
from pycognito.utils import RequestsSrpAuth, TokenType

Import exceptions:

from pycognito.exceptions import (
    TokenVerificationException,
    MFAChallengeException,
    ForceChangePasswordException
)

Basic Usage

from pycognito import Cognito

# Create Cognito instance
u = Cognito(
    user_pool_id='your-user-pool-id',
    client_id='your-client-id',
    username='bob'
)

# Authenticate user
u.authenticate(password='bobs-password')

# Access tokens after authentication
print(u.access_token)
print(u.id_token)
print(u.refresh_token)

# Get user information
user = u.get_user()
print(user.username)
print(user.email)

# Update user profile
u.update_profile({'given_name': 'Bob', 'family_name': 'Smith'})

Architecture

pycognito is built around several key components:

  • Cognito Class: Main interface for all AWS Cognito operations including authentication, user management, and token handling
  • UserObj/GroupObj: Object representations of Cognito users and groups with convenience methods
  • AWSSRP: Low-level implementation of AWS Secure Remote Password protocol for authentication
  • RequestsSrpAuth: Requests authentication plugin for automatic token handling in HTTP requests
  • Exception Classes: Specialized exceptions for different authentication and authorization scenarios

The library handles complex authentication flows, token verification, user profile management, and group operations while abstracting away the underlying AWS API complexity.

Capabilities

Authentication and Token Management

Core authentication functionality including SRP authentication, admin authentication, token verification, renewal, and logout operations. Handles complex authentication flows and token lifecycle management.

class Cognito:
    def authenticate(self, password: str, client_metadata: dict = None) -> None: ...
    def admin_authenticate(self, password: str) -> None: ...
    def verify_tokens(self) -> None: ...
    def check_token(self, renew: bool = True) -> bool: ...
    def renew_access_token(self) -> None: ...
    def logout(self) -> None: ...

Authentication and Token Management

User Management

Comprehensive user management including registration, profile updates, user retrieval, deletion, and administrative user operations. Supports both user-level and admin-level operations.

class Cognito:
    def register(self, username: str, password: str, attr_map: dict = None, client_metadata: dict = None) -> dict: ...
    def get_user(self, attr_map: dict = None) -> UserObj: ...
    def update_profile(self, attrs: dict, attr_map: dict = None) -> None: ...
    def admin_create_user(self, username: str, temporary_password: str = "", **kwargs) -> dict: ...
    def delete_user(self) -> None: ...

User Management

Password Management

Password-related operations including forgot password flows, password changes, confirmation codes, and password reset functionality with both user and admin capabilities.

class Cognito:
    def initiate_forgot_password(self) -> None: ...
    def confirm_forgot_password(self, confirmation_code: str, password: str) -> None: ...
    def change_password(self, previous_password: str, proposed_password: str) -> None: ...
    def admin_reset_password(self, username: str, client_metadata: dict = None) -> None: ...

Password Management

Multi-Factor Authentication (MFA)

Complete MFA support including software token (TOTP) and SMS MFA. Handles MFA setup, verification, preferences, and challenge responses for enhanced security.

class Cognito:
    def associate_software_token(self) -> str: ...
    def verify_software_token(self, code: str, device_name: str = "") -> bool: ...
    def set_user_mfa_preference(self, sms_mfa: bool, software_token_mfa: bool, preferred: str = None) -> None: ...
    def respond_to_software_token_mfa_challenge(self, code: str, mfa_tokens: dict = None) -> None: ...
    def respond_to_sms_mfa_challenge(self, code: str, mfa_tokens: dict = None) -> None: ...

Multi-Factor Authentication

Group Management

Group operations including group creation, retrieval, user group membership management, and administrative group operations for organizing users.

class Cognito:
    def get_group(self, group_name: str) -> GroupObj: ...
    def get_groups(self) -> list[GroupObj]: ...
    def admin_add_user_to_group(self, username: str, group_name: str) -> None: ...
    def admin_remove_user_from_group(self, username: str, group_name: str) -> None: ...
    def admin_list_groups_for_user(self, username: str) -> list[str]: ...

Group Management

Device Authentication

Device tracking and authentication support including device confirmation, status management, and device-based authentication flows for enhanced security.

class AWSSRP:
    def confirm_device(self, tokens: dict, device_name: str = None) -> tuple: ...
    def update_device_status(self, is_remembered: bool, access_token: str, device_key: str) -> str: ...
    def forget_device(self, access_token: str, device_key: str) -> str: ...

Device Authentication

SRP Authentication Protocol

Low-level Secure Remote Password protocol implementation providing the cryptographic foundation for secure authentication without transmitting passwords.

class AWSSRP:
    def __init__(self, username: str, password: str, pool_id: str, client_id: str, **kwargs): ...
    def authenticate_user(self, client=None, client_metadata: dict = None) -> dict: ...
    def set_new_password_challenge(self, new_password: str, client=None) -> dict: ...

SRP Authentication Protocol

HTTP Integration

Requests authentication plugin for seamless integration with HTTP clients, automatically handling token management and authentication headers.

class RequestsSrpAuth:
    def __init__(self, username: str = None, password: str = None, user_pool_id: str = None, 
                 client_id: str = None, cognito: Cognito = None, **kwargs): ...

HTTP Integration

Identity Provider Management

Administrative operations for managing external identity providers (SAML, OIDC, social providers) within the user pool for federated authentication.

class Cognito:
    def admin_create_identity_provider(self, pool_id: str, provider_name: str, provider_type: str, provider_details: dict, **kwargs) -> None: ...
    def admin_describe_identity_provider(self, pool_id: str, provider_name: str) -> dict: ...
    def admin_update_identity_provider(self, pool_id: str, provider_name: str, **kwargs) -> None: ...

User Pool Client Management

Operations for managing user pool application clients, including configuration retrieval and updates for client settings.

class Cognito:
    def describe_user_pool_client(self, pool_id: str, client_id: str) -> dict: ...
    def admin_update_user_pool_client(self, pool_id: str, client_id: str, **kwargs) -> None: ...

Types

Core Classes

class Cognito:
    """Main class for AWS Cognito User Pool operations."""
    def __init__(self, user_pool_id: str, client_id: str, user_pool_region: str = None,
                 username: str = None, id_token: str = None, refresh_token: str = None,
                 access_token: str = None, client_secret: str = None, access_key: str = None,
                 secret_key: str = None, session = None, botocore_config = None, 
                 boto3_client_kwargs: dict = None): ...
    
    # Properties
    user_pool_url: str
    id_claims: dict
    access_claims: dict

class UserObj:
    """Represents a Cognito user with attributes and operations."""
    def __init__(self, username: str, attribute_list: list, cognito_obj: Cognito,
                 metadata: dict = None, attr_map: dict = None): ...
    
    # Properties
    username: str
    sub: str
    email_verified: bool
    phone_number_verified: bool
    
    def save(self, admin: bool = False) -> None: ...
    def delete(self, admin: bool = False) -> None: ...

class GroupObj:
    """Represents a Cognito user group."""
    def __init__(self, group_data: dict, cognito_obj: Cognito): ...
    
    # Properties
    group_name: str
    description: str
    creation_date: datetime
    last_modified_date: datetime
    role_arn: str
    precedence: int

class AWSSRP:
    """AWS SRP authentication protocol implementation."""
    def __init__(self, username: str, password: str, pool_id: str, client_id: str, **kwargs): ...

class RequestsSrpAuth:
    """Requests authentication plugin for automatic Cognito authentication."""
    def __init__(self, username: str = None, password: str = None, **kwargs): ...

Enumerations

class TokenType(str, Enum):
    """Token types for authentication."""
    ID_TOKEN = "id_token"
    ACCESS_TOKEN = "access_token"

Exception Classes

class WarrantException(Exception):
    """Base class for all pyCognito exceptions."""

class TokenVerificationException(WarrantException):
    """Raised when token verification fails."""

class MFAChallengeException(WarrantException):
    """Base class for MFA challenge exceptions."""
    def get_tokens(self) -> dict: ...

class SoftwareTokenMFAChallengeException(MFAChallengeException):
    """Raised when Software Token MFA is required."""

class SMSMFAChallengeException(MFAChallengeException):
    """Raised when SMS MFA is required."""

class ForceChangePasswordException(WarrantException):
    """Raised when user is forced to change their password."""

Utility Functions

def cognito_to_dict(attr_list: list, attr_map: dict = None) -> dict:
    """Convert Cognito attribute list to dictionary."""

def dict_to_cognito(attributes: dict, attr_map: dict = None) -> list:
    """Convert dictionary to Cognito attribute format."""

def camel_to_snake(camel_str: str) -> str:
    """Convert CamelCase to snake_case."""

def snake_to_camel(snake_str: str) -> str:
    """Convert snake_case to CamelCase."""