Created
February 18, 2020 12:57
-
-
Save tuliocasagrande/87602902889f0ca0c98f0e9c9be33444 to your computer and use it in GitHub Desktop.
Responds to the new password challenge on Amazon Cognito
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def generate_password(length=16): | |
"""Generate a random alphanumeric password. | |
More recipes and best practices can be found here: | |
https://docs.python.org/3/library/secrets.html#recipes-and-best-practices. | |
Args: | |
length (int, optional): Password length. Defaults to 16. | |
Returns: | |
string: Generated password. | |
""" | |
import secrets | |
import string | |
alphabet = string.ascii_letters + string.digits | |
return ''.join(secrets.choice(alphabet) for i in range(length)) | |
def change_password_challenge(user_pool_id, client_id, username, temp_password, | |
new_password=None): | |
"""Responds to the new password challenge on Amazon Cognito. | |
More information here: | |
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html | |
Args: | |
user_pool_id (string): The ID of the Amazon Cognito user pool. | |
client_id (string): The app client ID. | |
username (string): Username. | |
temp_password (string): Current password. | |
new_password (string, optional): New password. If None, generates a random password. Defaults to None. | |
Raises: | |
Exception: If there's no challenge or if the challenge is not NEW_PASSWORD_REQUIRED | |
Returns: | |
(string, string, dict): (username, new_password, challenge_response) | |
""" | |
if new_password is None: | |
generate_password() | |
cognito = boto3.client('cognito-idp') | |
auth_response = cognito.admin_initiate_auth( | |
UserPoolId=user_pool_id, | |
ClientId=client_id, | |
AuthFlow='ADMIN_NO_SRP_AUTH', | |
AuthParameters={ | |
'USERNAME': username, | |
'PASSWORD': temp_password | |
} | |
) | |
if 'ChallengeName' not in auth_response: | |
raise Exception('This user has already changed the password') | |
if auth_response['ChallengeName'] != 'NEW_PASSWORD_REQUIRED': | |
raise Exception("This script supports only the 'NEW_PASSWORD_REQUIRED' challenge") | |
challenge_response = cognito.admin_respond_to_auth_challenge( | |
UserPoolId=user_pool_id, | |
ClientId=client_id, | |
ChallengeName=auth_response['ChallengeName'], | |
Session=auth_response['Session'], | |
ChallengeResponses={ | |
'USERNAME': username, | |
'NEW_PASSWORD': new_password | |
} | |
) | |
print('Password changed!') | |
print(f'USERNAME={username}') | |
print(f'PASSWORD={new_password}') | |
return username, new_password, challenge_response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment