Python class to integrate Boto3's Cognito client so it is easy to login users with SRP support.
—
Password-related operations for AWS Cognito User Pools, including forgot password flows, password changes, confirmation codes, new password challenges, and administrative password reset functionality. Provides both user-initiated and admin-initiated password management capabilities.
Initiate and complete the forgot password process using confirmation codes sent via email or SMS.
def initiate_forgot_password(self) -> None:
"""
Send a verification code to the user to change their password.
Actions:
- Sends verification code via email or SMS (based on user pool config)
- Code expires after configured time period (usually 24 hours)
Note:
Uses the username set on the Cognito instance.
User pool must be configured with email/SMS delivery.
"""
def confirm_forgot_password(self, confirmation_code: str, password: str) -> None:
"""
Complete the forgot password flow with verification code and new password.
Args:
confirmation_code (str): Code received via email/SMS
password (str): New password (must meet pool requirements)
Actions:
- Validates confirmation code
- Sets new password
- Updates instance password attribute
Raises:
Exception: If code is invalid, expired, or password doesn't meet requirements
"""Usage Example:
from pycognito import Cognito
# Initialize with username
u = Cognito('your-user-pool-id', 'your-client-id', username='john.doe')
# Initiate forgot password
u.initiate_forgot_password()
print("Password reset code sent to your registered email/phone")
# User receives code and provides new password
code = input("Enter confirmation code: ")
new_password = input("Enter new password: ")
# Complete password reset
u.confirm_forgot_password(code, new_password)
print("Password successfully reset!")
# User can now authenticate with new password
u.authenticate(password=new_password)Change password for authenticated users who know their current password.
def change_password(self, previous_password: str, proposed_password: str) -> None:
"""
Change the user's password (requires authentication).
Args:
previous_password (str): Current password for verification
proposed_password (str): New password (must meet pool requirements)
Requirements:
- User must be authenticated (valid access token)
- Previous password must be correct
- New password must meet user pool policy
Actions:
- Validates current password
- Sets new password
- Updates instance password attribute
Raises:
Exception: If current password is wrong or new password invalid
"""Usage Example:
# User must be authenticated first
u = Cognito('pool-id', 'client-id', username='user')
u.authenticate(password='current-password')
# Change password
u.change_password(
previous_password='current-password',
proposed_password='new-secure-password'
)
print("Password changed successfully!")Reset user passwords using administrative privileges without requiring the current password.
def admin_reset_password(self, username: str, client_metadata: dict = None) -> None:
"""
Reset a user's password using admin privileges.
Args:
username (str): Username whose password to reset
client_metadata (dict, optional): Custom workflow metadata
Actions:
- Generates temporary password or triggers reset flow
- May send reset instructions to user
- User will be required to set new password on next login
Note:
Exact behavior depends on user pool configuration:
- May generate temporary password
- May trigger forgot password flow
- May require user to set password on next login
"""Usage Example:
# Admin resets user password
u = Cognito('pool-id', 'client-id')
u.admin_reset_password('target-username')
print("Password reset initiated for user")
# User will need to set new password on next loginHandle the new password required challenge, typically triggered for users with temporary passwords or when forced password changes are required.
def new_password_challenge(self, password: str, new_password: str) -> None:
"""
Respond to new password challenge using SRP protocol.
Args:
password (str): Current/temporary password
new_password (str): New permanent password
Use cases:
- User logging in with temporary password (admin created)
- User forced to change password due to policy
- First-time login after admin user creation
Actions:
- Validates current password
- Sets new permanent password
- Completes authentication flow
- Sets tokens on successful completion
"""Usage Example:
from pycognito.exceptions import ForceChangePasswordException
u = Cognito('pool-id', 'client-id', username='new-user')
try:
u.authenticate(password='temporary-password')
except ForceChangePasswordException:
# User must set new password
new_password = input("Set your new password: ")
u.new_password_challenge(
password='temporary-password',
new_password=new_password
)
print("New password set successfully!")Send and validate verification codes for email or phone number changes.
def send_verification(self, attribute: str = "email") -> None:
"""
Send attribute verification code to the user.
Args:
attribute (str): Attribute to verify ("email" or "phone_number")
Actions:
- Sends verification code to the specified attribute
- Code expires after configured time period
Requirements:
- User must be authenticated
- Attribute must be configured for verification in user pool
"""
def validate_verification(self, confirmation_code: str, attribute: str = "email") -> dict:
"""
Verify user attribute using confirmation code.
Args:
confirmation_code (str): Code received via email/SMS
attribute (str): Attribute being verified ("email" or "phone_number")
Returns:
dict: Verification response from AWS Cognito
Actions:
- Validates confirmation code
- Marks attribute as verified
- Updates user's verification status
"""Usage Example:
# Send verification code for email change
u.send_verification("email")
print("Verification code sent to your email")
# User provides verification code
code = input("Enter verification code: ")
response = u.validate_verification(code, "email")
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
print("Email verified successfully!")from pycognito import Cognito
def forgot_password_flow(username):
"""Complete forgot password flow with user interaction."""
u = Cognito('pool-id', 'client-id', username=username)
try:
# Step 1: Initiate forgot password
u.initiate_forgot_password()
print(f"Password reset code sent to registered contact method")
# Step 2: Get code from user
code = input("Enter the confirmation code: ")
new_password = input("Enter your new password: ")
# Step 3: Complete password reset
u.confirm_forgot_password(code, new_password)
print("Password reset successfully!")
# Step 4: User can now login with new password
u.authenticate(password=new_password)
print("Authentication successful with new password!")
except Exception as e:
print(f"Password reset failed: {e}")
# Usage
forgot_password_flow('john.doe')def admin_password_management():
"""Admin manages user passwords."""
u = Cognito('pool-id', 'client-id')
# Create user with temporary password
response = u.admin_create_user(
username='newemployee',
temporary_password='TempPass123!',
email='employee@company.com'
)
print("User created with temporary password")
# Later, if user has issues, admin can reset
u.admin_reset_password('newemployee')
print("Password reset initiated for user")
admin_password_management()from pycognito.exceptions import ForceChangePasswordException
def new_user_login(username, temp_password):
"""Handle new user first login with temporary password."""
u = Cognito('pool-id', 'client-id', username=username)
try:
u.authenticate(password=temp_password)
print("Login successful!")
except ForceChangePasswordException:
print("You must set a new password")
# Get new password from user
new_password = input("Enter your new password: ")
confirm_password = input("Confirm new password: ")
if new_password != confirm_password:
print("Passwords don't match!")
return
# Set new password
u.new_password_challenge(
password=temp_password,
new_password=new_password
)
print("New password set! You are now logged in.")
print(f"Access token: {u.access_token}")
# Usage for new employee
new_user_login('newemployee', 'TempPass123!')def secure_password_change(u):
"""Secure password change with validation."""
# Verify user is authenticated
if not u.access_token:
print("Please authenticate first")
return
# Get current password for verification
current_password = input("Enter current password: ")
new_password = input("Enter new password: ")
confirm_password = input("Confirm new password: ")
# Validate passwords match
if new_password != confirm_password:
print("New passwords don't match!")
return
try:
u.change_password(current_password, new_password)
print("Password changed successfully!")
# Update any stored password reference
u.password = new_password
except Exception as e:
print(f"Password change failed: {e}")
# Usage
u = Cognito('pool-id', 'client-id', username='user')
u.authenticate(password='current-password')
secure_password_change(u)def update_and_verify_email(u, new_email):
"""Update email and handle verification."""
try:
# Update email attribute
u.update_profile({'email': new_email})
print(f"Email updated to {new_email}")
# Send verification code
u.send_verification("email")
print("Verification code sent to new email")
# Get verification code from user
code = input("Enter verification code: ")
# Verify email
response = u.validate_verification(code, "email")
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
print("Email verified successfully!")
else:
print("Email verification failed")
except Exception as e:
print(f"Email update failed: {e}")
# Usage
u = Cognito('pool-id', 'client-id', username='user')
u.authenticate(password='password')
update_and_verify_email(u, 'newemail@example.com')Install with Tessl CLI
npx tessl i tessl/pypi-pycognito