### Install pyCognito Source: https://context7.com/nabucasa/pycognito/llms.txt Install the pyCognito library using pip. Ensure you are using Python 3.9-3.12. ```bash pip install pycognito ``` -------------------------------- ### Associate Software Token Source: https://github.com/nabucasa/pycognito/blob/master/README.md Begins the setup of time-based one-time password (TOTP) multi-factor authentication (MFA) for a user. ```APIDOC ## POST /associate-software-token ### Description Begins the setup of time-based one-time password (TOTP) multi-factor authentication (MFA) for a user. ### Method POST ### Endpoint /associate-software-token ### Parameters #### Request Body - **access_token** (string) - Required - The access token of the user. ### Request Example ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', id_token='id-token', refresh_token='refresh-token', access_token='access-token') secret_code = u.associate_software_token() # Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code. ``` ### Response #### Success Response (200) - **secret_code** (string) - The secret code to issue the software token MFA code. #### Response Example ```json { "secret_code": "1234567890abcdef" } ``` ``` -------------------------------- ### Get User Object Source: https://github.com/nabucasa/pycognito/blob/master/README.md Returns an instance of the specified user class. ```python u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') u.get_user_obj(username='bjones', attribute_list=[{'Name': 'string','Value': 'string'},], metadata={}, attr_map={"given_name":"first_name","family_name":"last_name"} ) ``` -------------------------------- ### Initialize Cognito with Tokens Source: https://github.com/nabucasa/pycognito/blob/master/README.md Instantiate the Cognito class with existing tokens. This is useful for creating a new Cognito instance when a user has already authenticated, for example, in a web application's view. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', id_token='your-id-token', refresh_token='your-refresh-token', access_token='your-access-token') u.verify_tokens() # See method doc below; may throw an exception ``` -------------------------------- ### Get User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves all attributes for a given user. It fetches user information using Boto3 and constructs a user object. ```APIDOC ## GET /users/{username} ### Description Retrieves all attributes for a given user. It fetches user information using Boto3 and constructs a user object. ### Method GET ### Endpoint /users/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user. #### Query Parameters - **attr_map** (dict) - Optional - Dictionary map from Cognito attributes to attribute names we would like to show to our users. ### Request Example ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', username='bob') user = u.get_user(attr_map={"given_name":"first_name","family_name":"last_name"}) ``` ### Response #### Success Response (200) - **user_object** (object) - An object representing the user with their attributes. #### Response Example ```json { "user_object": { "username": "bob", "first_name": "Robert", "last_name": "Smith" } } ``` ``` -------------------------------- ### Get Users Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves a list of users within the user pool. ```APIDOC ## GET /users ### Description Retrieves a list of users within the user pool. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **attr_map** (dict) - Optional - Dictionary map from Cognito attributes to attribute names we would like to show to our users. ### Request Example ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') user = u.get_users(attr_map={"given_name":"first_name","family_name":"last_name"}) ``` ### Response #### Success Response (200) - **users** (list) - A list of user objects. #### Response Example ```json { "users": [ { "username": "alice", "first_name": "Alice" }, { "username": "bob", "first_name": "Robert" } ] } ``` ``` -------------------------------- ### Manage User Profiles with PyCognito Source: https://context7.com/nabucasa/pycognito/llms.txt Get and update user profile attributes. Requires an initialized Cognito object with authentication tokens. ```python from pycognito import Cognito u = Cognito( 'us-east-1_XXXXXXXXX', 'your-client-id', id_token='id-token', refresh_token='refresh-token', access_token='access-token' ) # Get current user with attribute mapping user = u.get_user(attr_map={'given_name': 'first_name', 'family_name': 'last_name'}) print(user.username) print(user.first_name) # Mapped from given_name print(user.email) # Update profile u.update_profile( {'given_name': 'Jonathan', 'family_name': 'Smith'}, attr_map={'given_name': 'first_name', 'family_name': 'last_name'} ) # Send verification email/SMS u.send_verification(attribute='email') # Validate verification code u.validate_verification('123456', attribute='email') ``` -------------------------------- ### Associate Software Token for MFA with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Initiates the setup for Time-based One-Time Password (TOTP) Multi-Factor Authentication (MFA) by generating a secret code. This code should be displayed to the user for entry into a TOTP generator. ```python from pycognito import Cognito #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') secret_code = u.associate_software_token() # Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code. ``` -------------------------------- ### Get Group Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves all attributes for a specified group. Requires developer credentials. ```APIDOC ## GET /groups/{group_name} ### Description Retrieves all attributes for a specified group. Requires developer credentials. ### Method GET ### Endpoint /groups/{group_name} ### Parameters #### Path Parameters - **group_name** (string) - Required - The name of the group. ### Request Example ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') group = u.get_group(group_name='some_group_name') ``` ### Response #### Success Response (200) - **group_object** (object) - An object representing the group with its attributes. #### Response Example ```json { "group_object": { "GroupName": "some_group_name", "Description": "A sample group", "Precedence": 5 } } ``` ``` -------------------------------- ### Get Groups Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves a list of groups within the user pool. Requires developer credentials. ```APIDOC ## GET /groups ### Description Retrieves a list of groups within the user pool. Requires developer credentials. ### Method GET ### Endpoint /groups ### Parameters None ### Request Example ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') groups = u.get_groups() ``` ### Response #### Success Response (200) - **groups** (list) - A list of group objects. #### Response Example ```json { "groups": [ { "GroupName": "admin", "Description": "Administrators", "Precedence": 1 }, { "GroupName": "user", "Description": "Regular users", "Precedence": 2 } ] } ``` ``` -------------------------------- ### Get Group Object Source: https://github.com/nabucasa/pycognito/blob/master/README.md Returns an instance of the specified group_class. ```APIDOC ## POST /groups/object ### Description Returns an instance of the specified group_class. ### Method POST ### Endpoint /groups/object ### Parameters #### Request Body - **group_data** (dict) - Required - Dictionary with group's attributes. - **GroupName** (string) - Required - The name of the group. - **Description** (string) - Optional - The description of the group. - **Precedence** (integer) - Optional - The precedence of the group. ### Request Example ```python u = Cognito('your-user-pool-id', 'your-client-id') group_data = {'GroupName': 'user_group', 'Description': 'description', 'Precedence': 1} group_obj = u.get_group_obj(group_data) ``` ### Response #### Success Response (200) - **group_object** (object) - An object representing the group. #### Response Example ```json { "group_object": { "GroupName": "user_group", "Description": "description", "Precedence": 1 } } ``` ``` -------------------------------- ### Get All Groups in User Pool with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Fetches a list of all groups within the user pool. Developer credentials are required for this operation. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') groups = u.get_groups() ``` -------------------------------- ### Get List of Users in User Pool with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Fetches a list of users within the user pool. The attr_map argument can be used to customize attribute display names. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') user = u.get_users(attr_map={"given_name":"first_name","family_name":"last_name"}) ``` -------------------------------- ### Get Specific Group Attributes with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves attributes for a specific group by its name. This operation requires developer credentials. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') group = u.get_group(group_name='some_group_name') ``` -------------------------------- ### Get User Attributes with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Retrieves a user's attributes from Cognito. Use attr_map to rename attributes for display. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', username='bob') user = u.get_user(attr_map={"given_name":"first_name","family_name":"last_name"}) ``` -------------------------------- ### Initialize Cognito with All Arguments Source: https://github.com/nabucasa/pycognito/blob/master/README.md Instantiate the Cognito class with all possible arguments. This is useful for comprehensive configuration when all parameters are known. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', client_secret='optional-client-secret', username='optional-username', id_token='optional-id-token', refresh_token='optional-refresh-token', access_token='optional-access-token', access_key='optional-access-key', secret_key='optional-secret-key') ``` -------------------------------- ### Implement Device Authentication and Tracking Source: https://context7.com/nabucasa/pycognito/llms.txt Configures device tracking, confirms devices, and performs authentication using device keys and passwords. ```python import boto3 from pycognito.aws_srp import AWSSRP client = boto3.client('cognito-idp', region_name='us-east-1') # Initial authentication aws = AWSSRP( username='bob', password='bobs-password', pool_id='us-east-1_XXXXXXXXX', client_id='your-client-id', client=client ) tokens = aws.authenticate_user() # Get device keys from response device_key = tokens['AuthenticationResult']['NewDeviceMetadata']['DeviceKey'] device_group_key = tokens['AuthenticationResult']['NewDeviceMetadata']['DeviceGroupKey'] # Confirm the device response, device_password = aws.confirm_device(tokens, device_name='My Laptop') # Update device status (remembered or not) aws.update_device_status( is_remembered=True, access_token=tokens['AuthenticationResult']['AccessToken'], device_key=device_key ) # Subsequent authentication with device aws_with_device = AWSSRP( username='bob', password='bobs-password', pool_id='us-east-1_XXXXXXXXX', client_id='your-client-id', client=client, device_key=device_key, device_group_key=device_group_key, device_password=device_password ) tokens = aws_with_device.authenticate_user() # Forget device aws.forget_device( access_token=tokens['AuthenticationResult']['AccessToken'], device_key=device_key ) ``` -------------------------------- ### Register New User Source: https://context7.com/nabucasa/pycognito/llms.txt Register a new user with base and custom attributes. The client ID must have write permissions for the attributes. Confirm sign-up using the provided code. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') # Set base attributes u.set_base_attributes(email='user@example.com', given_name='John', family_name='Doe') # Add custom attributes (must be configured in User Pool) u.add_custom_attributes(department='engineering', employee_id='12345') # Register the user response = u.register('johndoe', 'SecurePassword123!') # Returns: {'UserConfirmed': False, 'CodeDeliveryDetails': {'Destination': 'u***@e***.com', 'DeliveryMedium': 'EMAIL', 'AttributeName': 'email'}} # Confirm sign up with verification code u.confirm_sign_up('123456', username='johndoe') ``` -------------------------------- ### Set Up Software Token MFA with PyCognito Source: https://context7.com/nabucasa/pycognito/llms.txt Set up and manage Time-based One-Time Password (TOTP) multi-factor authentication. Requires an initialized Cognito object with authentication tokens. ```python from pycognito import Cognito u = Cognito( 'us-east-1_XXXXXXXXX', 'your-client-id', id_token='id-token', refresh_token='refresh-token', access_token='access-token' ) # Get secret code for TOTP setup secret_code = u.associate_software_token() print(f"Enter this code in your authenticator app: {secret_code}") # Verify the TOTP code from authenticator app code = '123456' # From Google Authenticator, Authy, etc. success = u.verify_software_token(code, device_name='My iPhone') print(f"MFA setup successful: {success}") # Set MFA preferences u.set_user_mfa_preference( sms_mfa=True, software_token_mfa=True, preferred='SOFTWARE_TOKEN' # or 'SMS' ) ``` -------------------------------- ### Initialize Cognito Class Source: https://context7.com/nabucasa/pycognito/llms.txt Instantiate the Cognito class with user pool ID and client ID. Optional parameters include username, tokens, client secret, and AWS credentials. ```python from pycognito import Cognito # Basic initialization with user pool and client ID only u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') ``` ```python # With username for authentication u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id', username='bob') ``` ```python # With existing tokens (after previous authentication) u = Cognito( 'us-east-1_XXXXXXXXX', 'your-client-id', id_token='your-id-token', refresh_token='your-refresh-token', access_token='your-access-token' ) ``` ```python # With client secret and AWS credentials u = Cognito( 'us-east-1_XXXXXXXXX', 'your-client-id', client_secret='optional-client-secret', username='bob', access_key='your-aws-access-key', secret_key='your-aws-secret-key' ) ``` -------------------------------- ### Handle New Password Required Challenge Source: https://context7.com/nabucasa/pycognito/llms.txt Demonstrates how to catch an authentication exception and respond with a new password challenge. ```python try: tokens = aws.authenticate_user() except Exception: tokens = aws.set_new_password_challenge('new-secure-password') ``` -------------------------------- ### Initialize Cognito with Username Source: https://github.com/nabucasa/pycognito/blob/master/README.md Instantiate the Cognito class with a username. This is typically used when the user has not yet logged in and you intend to authenticate using SRP or admin_authenticate. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', username='bob') ``` -------------------------------- ### Register a User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Registers a new user to the user pool. Ensure the client ID has write permissions for the specified attributes. ```python from pycognito import Cognito u = Cognito('your-user-pool-id', 'your-client-id') u.set_base_attributes(email='you@you.com', some_random_attr='random value') u.register('username', 'password') ``` ```python from pycognito import Cognito u = Cognito('your-user-pool-id', 'your-client-id') u.set_base_attributes(email='you@you.com', some_random_attr='random value') u.add_custom_attributes(state='virginia', city='Centreville') u.register('username', 'password') ``` -------------------------------- ### Initialize Cognito with User Pool ID and Client ID Source: https://github.com/nabucasa/pycognito/blob/master/README.md Instantiate the Cognito class using only the user pool ID and client ID. This is suitable for operations that only require user pool information, such as listing users. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') ``` -------------------------------- ### List Users and Groups with PyCognito Source: https://context7.com/nabucasa/pycognito/llms.txt Retrieve users and groups from the User Pool. Requires appropriate permissions. Initialize Cognito with pool ID and client ID. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') # Get all users in the pool users = u.get_users(attr_map={'given_name': 'first_name', 'family_name': 'last_name'}) for user in users: print(f"{user.username}: {user.first_name} {user.last_name}") # Get all groups groups = u.get_groups() for group in groups: print(f"{group.group_name}: {group.description}") # Get a specific group group = u.get_group(group_name='admins') print(group.precedence) ``` -------------------------------- ### Configure User Pool Clients Source: https://context7.com/nabucasa/pycognito/llms.txt Retrieves and updates app client settings for a user pool. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') # Get client configuration client_config = u.describe_user_pool_client('us-east-1_XXXXXXXXX', 'your-client-id') print(client_config['ClientName']) print(client_config['ExplicitAuthFlows']) # Update client configuration u.admin_update_user_pool_client( pool_id='us-east-1_XXXXXXXXX', client_id='your-client-id', ExplicitAuthFlows=['ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'], SupportedIdentityProviders=['COGNITO', 'MySAMLProvider'] ) ``` -------------------------------- ### Authenticate a User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Authenticates a user and populates the instance with token attributes upon success. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', username='bob') u.authenticate(password='bobs-password') ``` -------------------------------- ### Set User MFA Preference in Python Source: https://github.com/nabucasa/pycognito/blob/master/README.md Configures enabled MFA methods and sets the preferred authentication priority. ```python from pycognito import Cognito #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') # SMS MFA are valid. SMS preference. u.set_user_mfa_preference(True, False, "SMS") # Software Token MFA are valid. Software token preference. u.set_user_mfa_preference(False, True, "SOFTWARE_TOKEN") # Both Software Token MFA and SMS MFA are valid. Software token preference u.set_user_mfa_preference(True, True, "SOFTWARE_TOKEN") # Both Software Token MFA and SMS MFA are disabled. u.set_user_mfa_preference(False, False) ``` -------------------------------- ### Respond to Software Token MFA Challenge in Python Source: https://github.com/nabucasa/pycognito/blob/master/README.md Handles the MFA challenge during authentication, including scenarios where the Cognito instance is recreated. ```python from pycognito import Cognito from pycognito.exceptions import SoftwareTokenMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SoftwareTokenMFAChallengeException as error: code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).') u.respond_to_software_token_mfa_challenge(code) ``` ```python from pycognito import Cognito from pycognito.exceptions import SoftwareTokenMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SoftwareTokenMFAChallengeException as error: mfa_tokens = error.get_tokens() u = Cognito('your-user-pool-id','your-client-id', username='bob') code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).') u.respond_to_software_token_mfa_challenge(code, mfa_tokens) ``` -------------------------------- ### Initiate Forgot Password Source: https://github.com/nabucasa/pycognito/blob/master/README.md Sends a verification code to the user for password recovery. ```python u = Cognito('your-user-pool-id','your-client-id', username='bob') u.initiate_forgot_password() ``` -------------------------------- ### Confirm Sign Up Source: https://github.com/nabucasa/pycognito/blob/master/README.md Confirms a user account using a verification code. ```APIDOC ## Confirm Sign Up ### Description Use the confirmation code that is sent via email or text to confirm the user's account. ### Parameters #### Request Body - **confirmation_code** (string) - Required - Confirmation code sent via text or email - **username** (string) - Required - User's username ``` -------------------------------- ### Low-Level SRP Authentication with AWSSRP Source: https://context7.com/nabucasa/pycognito/llms.txt Use the AWSSRP class directly for more control over the SRP authentication flow. Requires boto3 client and Cognito pool/client details. ```python import boto3 from pycognito.aws_srp import AWSSRP client = boto3.client('cognito-idp', region_name='us-east-1') aws = AWSSRP( username='bob', password='bobs-password', pool_id='us-east-1_XXXXXXXXX', client_id='your-client-id', client=client, client_secret='optional-client-secret' # If configured ) # Authenticate and get tokens tokens = aws.authenticate_user() print(tokens['AuthenticationResult']['AccessToken']) print(tokens['AuthenticationResult']['IdToken']) print(tokens['AuthenticationResult']['RefreshToken']) ``` -------------------------------- ### Confirm Sign Up Source: https://github.com/nabucasa/pycognito/blob/master/README.md Confirms a user account using a verification code sent via email or text. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id') u.confirm_sign_up('users-conf-code',username='bob') ``` -------------------------------- ### Manage Identity Providers Source: https://context7.com/nabucasa/pycognito/llms.txt Provides administrative methods to create, describe, and update SAML identity providers. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') # Create a SAML identity provider u.admin_create_identity_provider( pool_id='us-east-1_XXXXXXXXX', provider_name='MySAMLProvider', provider_type='SAML', provider_details={ 'MetadataURL': 'https://idp.example.com/metadata.xml', 'IDPSignout': 'true' }, AttributeMapping={ 'email': 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress' } ) # Describe an identity provider provider = u.admin_describe_identity_provider('us-east-1_XXXXXXXXX', 'MySAMLProvider') print(provider['IdentityProvider']) # Update identity provider u.admin_update_identity_provider( pool_id='us-east-1_XXXXXXXXX', provider_name='MySAMLProvider', ProviderDetails={'IDPSignout': 'false'} ) ``` -------------------------------- ### Admin User Management with PyCognito Source: https://context7.com/nabucasa/pycognito/llms.txt Perform administrative operations on users. Requires IAM admin permissions. Initialize Cognito with pool ID and client ID. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') # Create a user as admin response = u.admin_create_user( username='newuser', temporary_password='TempPass123!', email='newuser@example.com', given_name='New', family_name='User' ) # Confirm sign up without verification code u.admin_confirm_sign_up(username='newuser') # Get user details as admin u.username = 'newuser' user = u.admin_get_user(attr_map={'given_name': 'first_name'}) print(user.first_name) # Enable/disable users u.admin_enable_user('newuser') u.admin_disable_user('newuser') # Reset user password u.admin_reset_password('newuser', client_metadata={'source': 'admin_portal'}) # Add/remove user from groups u.admin_add_user_to_group('newuser', 'admins') u.admin_remove_user_from_group('newuser', 'admins') # List groups for a user groups = u.admin_list_groups_for_user('newuser') print(groups) # ['admins', 'users'] # Delete user u.admin_delete_user() ``` -------------------------------- ### Device Authentication and Management Source: https://github.com/nabucasa/pycognito/blob/master/README.md Methods for confirming devices, updating device status, and authenticating using device keys. ```APIDOC ## POST /confirm_device ### Description Confirms a device with the Cognito user pool. ### Parameters #### Request Body - **tokens** (object) - Required - **DeviceName** (string) - Optional ## POST /update_device_status ### Description Updates whether a device should be remembered. ### Parameters #### Request Body - **is_remembered** (boolean) - Required - **access_token** (string) - Required - **device_key** (string) - Required ``` -------------------------------- ### Verify Software Token in Python Source: https://github.com/nabucasa/pycognito/blob/master/README.md Validates a 6-digit TOTP code to enable Software Token MFA for a user. ```python from pycognito import Cognito #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') secret_code = u.associate_software_token() # Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code. code = input('Enter the 6-digit code.') device_name = input('Enter the device name') u.verify_software_token(code, device_name) ``` -------------------------------- ### Respond to Software Token MFA Challenge Source: https://github.com/nabucasa/pycognito/blob/master/README.md Responds to a Software Token MFA challenge that is requested during the login process. This is used when a user is prompted for their TOTP code after providing their password. ```APIDOC ## Respond to Software Token MFA challenge ### Description Responds when a Software Token MFA challenge is requested at login. ### Method Not applicable (Python function call) ### Endpoint Not applicable (Python function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pycognito import Cognito from pycognito.exceptions import SoftwareTokenMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SoftwareTokenMFAChallengeException as error: code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).') u.respond_to_software_token_mfa_challenge(code) ``` ### Response #### Success Response (200) None (operation completes authentication) #### Response Example None ``` ```APIDOC ## Respond to Software Token MFA challenge (with mfa_tokens) ### Description Responds to a Software Token MFA challenge, optionally using pre-fetched MFA tokens if the Cognito instance was recreated. ### Method Not applicable (Python function call) ### Endpoint Not applicable (Python function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pycognito import Cognito from pycognito.exceptions import SoftwareTokenMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SoftwareTokenMFAChallengeException as error: mfa_tokens = error.get_tokens() u = Cognito('your-user-pool-id','your-client-id', username='bob') code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).') u.respond_to_software_token_mfa_challenge(code, mfa_tokens) ``` ### Response #### Success Response (200) None (operation completes authentication) #### Response Example None ``` -------------------------------- ### Confirm a device Source: https://github.com/nabucasa/pycognito/blob/master/README.md Confirms a device using the AWSSRP instance and returns the device password for future authentication. ```python response, device_password = aws.confirm_device(tokens=tokens) ``` -------------------------------- ### Authenticate a device Source: https://github.com/nabucasa/pycognito/blob/master/README.md Authenticates a device by providing device credentials to the AWSSRP class. ```python import boto3 from pycognito.aws_srp import AWSSRP client = boto3.client('cognito-idp') aws = AWSSRP(username='username', password='password', pool_id='user_pool_id', client_id='client_id', client=client, device_key="device_key", device_group_key="device_group_key", device_password="device_password") tokens = aws.authenticate_user() ``` -------------------------------- ### Verify Tokens Source: https://github.com/nabucasa/pycognito/blob/master/README.md Verifies the current id_token and access_token. An exception will be thrown if they do not pass verification. ```APIDOC ## POST /token/verify ### Description Verifies the current id_token and access_token. An exception will be thrown if they do not pass verification. ### Method POST ### Endpoint /token/verify ### Parameters #### Request Body - **id_token** (string) - Required - The ID token to verify. - **access_token** (string) - Required - The access token to verify. ### Request Example ```python u = Cognito('your-user-pool-id','your-client-id', id_token='id-token', refresh_token='refresh-token', access_token='access-token') u.check_tokens() # Optional, if you want to maybe renew the tokens u.verify_tokens() ``` ### Response #### Success Response (200) - **verification_status** (string) - Indicates that tokens have been verified. #### Response Example ```json { "verification_status": "Tokens verified successfully." } ``` ``` -------------------------------- ### Authenticate User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Authenticates a user and retrieves tokens. ```APIDOC ## Authenticate User ### Description Authenticates a user. Upon success, the instance is populated with id_token, refresh_token, access_token, expires_in, expires_datetime, and token_type. ### Parameters #### Request Body - **password** (string) - Required - User's password ``` -------------------------------- ### Handle MFA Challenges During Authentication Source: https://context7.com/nabucasa/pycognito/llms.txt Respond to MFA challenges that occur during the authentication flow. Catches specific MFA exceptions and prompts for the necessary code. ```python from pycognito import Cognito from pycognito.exceptions import SoftwareTokenMFAChallengeException, SMSMFAChallengeException u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SoftwareTokenMFAChallengeException as e: # User has software token MFA enabled mfa_tokens = e.get_tokens() code = input('Enter TOTP code from authenticator app: ') u.respond_to_software_token_mfa_challenge(code, mfa_tokens) except SMSMFAChallengeException as e: # User has SMS MFA enabled mfa_tokens = e.get_tokens() code = input('Enter code received via SMS: ') u.respond_to_sms_mfa_challenge(code, mfa_tokens) # After successful MFA, tokens are available print(u.access_token) ``` -------------------------------- ### Create Group Object with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Instantiates a group object using provided group data. Requires a dictionary containing group attributes like GroupName and Description. ```python u = Cognito('your-user-pool-id', 'your-client-id') group_data = {'GroupName': 'user_group', 'Description': 'description', 'Precedence': 1} group_obj = u.get_group_obj(group_data) ``` -------------------------------- ### Verify Software Token Source: https://github.com/nabucasa/pycognito/blob/master/README.md Verifies a 6-digit code generated by a TOTP application to enable Software Token MFA for a user. This is typically done after associating a software token with the user. ```APIDOC ## Verify Software Token ### Description Verify the 6-digit code issued based on the secret code issued by associate_software_token. If this validation is successful, Cognito will enable Software token MFA. ### Method Not applicable (Python function call) ### Endpoint Not applicable (Python function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pycognito import Cognito #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') secret_code = u.associate_software_token() # Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code. code = input('Enter the 6-digit code.') device_name = input('Enter the device name') u.verify_software_token(code, device_name) ``` ### Response #### Success Response (200) None (operation modifies user settings) #### Response Example None ``` -------------------------------- ### Admin Authenticate a User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Authenticates a user using admin super privileges. ```python from pycognito import Cognito u = Cognito('your-user-pool-id','your-client-id', username='bob') u.admin_authenticate(password='bobs-password') ``` -------------------------------- ### Set User MFA Preference Source: https://github.com/nabucasa/pycognito/blob/master/README.md Enables or disables MFA methods (SMS and Software Token) and sets the preferred MFA method for a user. This allows you to prioritize how MFA challenges are presented. ```APIDOC ## Set User MFA Preference ### Description Enable and prioritize Software Token MFA and SMS MFA. If both Software Token MFA and SMS MFA are invalid, the preference value will be ignored. ### Method Not applicable (Python function call) ### Endpoint Not applicable (Python function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pycognito import Cognito #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') # SMS MFA are valid. SMS preference. u.set_user_mfa_preference(True, False, "SMS") # Software Token MFA are valid. Software token preference. u.set_user_mfa_preference(False, True, "SOFTWARE_TOKEN") # Both Software Token MFA and SMS MFA are valid. Software token preference u.set_user_mfa_preference(True, True, "SOFTWARE_TOKEN") # Both Software Token MFA and SMS MFA are disabled. u.set_user_mfa_preference(False, False) ``` ### Response #### Success Response (200) None (operation modifies user settings) #### Response Example None ``` -------------------------------- ### Handle Cognito Authentication Exceptions Source: https://context7.com/nabucasa/pycognito/llms.txt Use these exception handlers to manage password change requirements and multi-factor authentication challenges during the login process. ```python from pycognito import Cognito from pycognito.exceptions import ( TokenVerificationException, ForceChangePasswordException, SoftwareTokenMFAChallengeException, SMSMFAChallengeException ) u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id', username='bob') try: u.authenticate(password='bobs-password') except ForceChangePasswordException: # User must change password on first login u.new_password_challenge('current-password', 'new-secure-password') except SoftwareTokenMFAChallengeException as e: # TOTP MFA required code = input('Enter TOTP code: ') u.respond_to_software_token_mfa_challenge(code, e.get_tokens()) except SMSMFAChallengeException as e: # SMS MFA required code = input('Enter SMS code: ') u.respond_to_sms_mfa_challenge(code, e.get_tokens()) # Token verification errors try: u.verify_tokens() except TokenVerificationException as e: print(f"Token verification failed: {e}") # Re-authenticate to get new tokens u.authenticate(password='bobs-password') ``` -------------------------------- ### Retrieve device keys Source: https://github.com/nabucasa/pycognito/blob/master/README.md Extracts DeviceKey and DeviceGroupKey from the authentication result for device tracking. ```python import boto3 from pycognito.aws_srp import AWSSRP client = boto3.client('cognito-idp') aws = AWSSRP(username='username', password='password', pool_id='user_pool_id', client_id='client_id', client=client) tokens = aws.authenticate_user() device_key = tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceKey"] device_group_key = tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceGroupKey"] ``` -------------------------------- ### Admin Authentication Source: https://context7.com/nabucasa/pycognito/llms.txt Authenticate users using admin privileges with the ADMIN_NO_SRP_AUTH flow. This requires appropriate IAM permissions. Tokens are available after successful authentication. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id', username='bob') # Admin authenticate - bypasses SRP u.admin_authenticate(password='bobs-password') # Tokens are available after authentication print(u.access_token) ``` -------------------------------- ### Configure COGNITO_JWKS Environment Variable Source: https://github.com/nabucasa/pycognito/blob/master/README.md Optional: Set the COGNITO_JWKS environment variable to a dictionary representing your user pool's JWKs. This is used for token validation. ```command line COGNITO_JWKS={"keys": [{"alg": "RS256","e": "AQAB","kid": "123456789ABCDEFGHIJKLMNOP","kty": "RSA","n": "123456789ABCDEFGHIJKLMNOP","use": "sig"},{"alg": "RS256","e": "AQAB","kid": "123456789ABCDEFGHIJKLMNOP","kty": "RSA","n": "123456789ABCDEFGHIJKLMNOP","use": "sig"}]} ``` -------------------------------- ### Respond to SMS MFA challenge Source: https://github.com/nabucasa/pycognito/blob/master/README.md Handles SMS MFA challenges during the authentication process. Requires catching the SMSMFAChallengeException. ```python from pycognito import Cognito from pycognito.exceptions import SMSMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SMSMFAChallengeException as error: code = input('Enter the 6-digit code you received by SMS.') u.respond_to_sms_mfa_challenge(code) ``` ```python from pycognito import Cognito from pycognito.exceptions import SMSMFAChallengeException #If you don't use your tokens then you will need to #use your username and password and call the authenticate method u = Cognito('your-user-pool-id','your-client-id', username='bob') try: u.authenticate(password='bobs-password') except SMSMFAChallengeException as error: mfa_tokens = error.get_tokens() u = Cognito('your-user-pool-id','your-client-id', username='bob') code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).') u.respond_to_sms_mfa_challenge(code, mfa_tokens) ``` -------------------------------- ### Verify and Manage Tokens Source: https://context7.com/nabucasa/pycognito/llms.txt Verify JWT tokens, check expiration, and automatically refresh tokens. Initialize with existing tokens to manage them. The `check_token` method can automatically renew expired tokens. ```python from pycognito import Cognito # Initialize with existing tokens u = Cognito( 'us-east-1_XXXXXXXXX', 'your-client-id', id_token='existing-id-token', refresh_token='existing-refresh-token', access_token='existing-access-token' ) # Verify tokens - raises TokenVerificationException if invalid u.verify_tokens() # Check if access token is expired and optionally renew expired = u.check_token(renew=True) # Automatically refreshes if expired # Manually renew access token using refresh token u.renew_access_token() ``` -------------------------------- ### Authenticate User with SRP Source: https://context7.com/nabucasa/pycognito/llms.txt Authenticate users using the Secure Remote Password (SRP) protocol. Tokens are automatically set upon successful authentication and are accessible as attributes. Verified claims are also available. ```python from pycognito import Cognito u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id', username='bob') # Authenticate - tokens are automatically set on success u.authenticate(password='bobs-password') # After authentication, tokens are available as attributes print(u.id_token) # JWT ID token print(u.access_token) # JWT access token print(u.refresh_token) # Refresh token for renewal print(u.token_type) # 'Bearer' # Verified claims are also available print(u.id_claims) # Dict of verified claims from ID token print(u.access_claims) # Dict of verified claims from access token ``` -------------------------------- ### Register User Source: https://github.com/nabucasa/pycognito/blob/master/README.md Registers a new user to the Cognito user pool. ```APIDOC ## Register User ### Description Registers a user to the user pool. Ensure the client ID has write permissions for the attributes being set. ### Parameters #### Request Body - **username** (string) - Required - User Pool username - **password** (string) - Required - User Pool password - **attr_map** (dict) - Optional - Attribute map to Cognito's attributes ``` -------------------------------- ### Verify ID and Access Tokens with PyCognito Source: https://github.com/nabucasa/pycognito/blob/master/README.md Verifies the integrity of the current id_token and access_token. This method also populates id_claims and access_claims. It's recommended to call this after check_tokens if both are used. ```python u = Cognito('your-user-pool-id','your-client-id', id_token='id-token',refresh_token='refresh-token', access_token='access-token') u.check_tokens() # Optional, if you want to maybe renew the tokens u.verify_tokens() ``` -------------------------------- ### Configure JWKS Caching via Environment Variables Source: https://context7.com/nabucasa/pycognito/llms.txt Set the COGNITO_JWKS environment variable to provide cached keys, preventing redundant network requests to AWS during token verification. ```python import os # Set COGNITO_JWKS environment variable with your user pool's JWKs # Find keys at: https://cognito-idp.{region}.amazonaws.com/{pool-id}/.well-known/jwks.json os.environ['COGNITO_JWKS'] = '{"keys": [{"alg": "RS256","e": "AQAB","kid": "abc123","kty": "RSA","n": "xyz...","use": "sig"}]}' from pycognito import Cognito # Cognito will use cached JWKS instead of fetching from AWS u = Cognito('us-east-1_XXXXXXXXX', 'your-client-id') ``` -------------------------------- ### Respond to SMS MFA Challenge Source: https://github.com/nabucasa/pycognito/blob/master/README.md Handles the response to an SMS MFA challenge during the authentication process. ```APIDOC ## POST /respond_to_sms_mfa_challenge ### Description Responds to an SMS MFA challenge requested during the login process. ### Parameters #### Request Body - **code** (string) - Required - 6-digit code received by SMS. - **mfa_tokens** (object) - Optional - MFA tokens stored in SMSMFAChallengeException, required if the Cognito instance has been regenerated. ``` -------------------------------- ### Send Verification Source: https://github.com/nabucasa/pycognito/blob/master/README.md Sends a verification email or text. ```APIDOC ## Send Verification ### Description Send verification email or text for either the email or phone attributes. ### Parameters #### Request Body - **attribute** (string) - Required - The attribute (email or phone) that needs to be verified ```