Skip to content

Instantly share code, notes, and snippets.

@aleksei140888
Created April 7, 2022 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aleksei140888/06de4ef62e7d4372ce60188a898973f3 to your computer and use it in GitHub Desktop.
Save aleksei140888/06de4ef62e7d4372ce60188a898973f3 to your computer and use it in GitHub Desktop.
The script helps to change the password for the cognito user and get access, id and resfresh tokens for it. (Please allow ALLOW_USER_PASSWORD_AUTH and ALLOW_USER_SRP_AUTH for your app_client)
import boto3
import logging
import botocore
from typing import Optional
from botocore.exceptions import ClientError
AWS_ACCESS_KEY_ID = 'AKIAS7AVEMA4RPAVEMAA'
AWS_SECRET_ACCESS_KEY = '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'
COGNITO_REGION_NAME = 'us-east-1'
COGNITO_CLIENT_ID = '6vulkjsdf43vfs3i6221der6q8'
COGNITO_POOL_ID = 'us-east-1_oLfgtVNnw'
USERNAME = 'test'
PASSWORD = 'testtest123'
NEW_PASSWORD = 'testtest!@#'
client = boto3.client(
"cognito-idp",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=COGNITO_REGION_NAME,
)
def change_password_challenge(username, temp_password, new_password):
auth_response = client.admin_initiate_auth(
UserPoolId=COGNITO_POOL_ID,
ClientId=COGNITO_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 = client.admin_respond_to_auth_challenge(
UserPoolId=COGNITO_POOL_ID,
ClientId=COGNITO_CLIENT_ID,
ChallengeName=auth_response['ChallengeName'],
Session=auth_response['Session'],
ChallengeResponses={
'USERNAME': username,
'NEW_PASSWORD': new_password
}
)
return username, new_password, challenge_response
def login_user_with_creds(email: str, password: str) -> Optional[dict]:
try:
response = client.initiate_auth(
ClientId=COGNITO_CLIENT_ID,
AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": email, "PASSWORD": password},
)
except (
client.exceptions.NotAuthorizedException,
client.exceptions.InvalidParameterException,
botocore.exceptions.ParamValidationError,
) as exc:
logging.warning("Can't login user", exc_info=exc)
return None
except ClientError as exc:
logging.error(*exc.args)
return None
response_fields_mapping = {
"AccessToken": "user_action_token",
"IdToken": "jwt_token",
"RefreshToken": "refresh_token",
}
try:
result = response["AuthenticationResult"]
tokens = {
result_token_name: result[response_token_name]
for response_token_name, result_token_name in response_fields_mapping.items()
}
except KeyError:
tokens = None
if not tokens:
logging.warning("Can't login user - invalid response from cognito: %r", response)
return tokens or None
change_password_challenge(USERNAME, PASSWORD, NEW_PASSWORD)
print(login_user_with_creds(USERNAME, NEW_PASSWORD))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment