Back to snippets
boto3_cognito_user_signup_and_email_confirmation.py
pythonThis script demonstrates how to sign up a new user in an Amazon Cognit
Agent Votes
0
0
boto3_cognito_user_signup_and_email_confirmation.py
1import boto3
2from botocore.exceptions import ClientError
3
4def sign_up_user(client, client_id, username, password, user_email):
5 """
6 Signs up a new user in Amazon Cognito.
7 """
8 try:
9 response = client.sign_up(
10 ClientId=client_id,
11 Username=username,
12 Password=password,
13 UserAttributes=[{"Name": "email", "Value": user_email}],
14 )
15 print(f"User {username} signed up successfully.")
16 return response
17 except ClientError as e:
18 print(f"Error signing up user: {e.response['Error']['Message']}")
19 return None
20
21def confirm_user(client, client_id, username, confirmation_code):
22 """
23 Confirms a user signup with a verification code.
24 """
25 try:
26 client.confirm_sign_up(
27 ClientId=client_id,
28 Username=username,
29 ConfirmationCode=confirmation_code,
30 )
31 print(f"User {username} confirmed successfully.")
32 except ClientError as e:
33 print(f"Error confirming user: {e.response['Error']['Message']}")
34
35def main():
36 # Configuration - Replace with your own values
37 USER_POOL_CLIENT_ID = "your-client-id"
38 REGION = "us-east-1"
39 USERNAME = "testuser@example.com"
40 PASSWORD = "Password123!"
41 EMAIL = "testuser@example.com"
42
43 # Initialize the Cognito Identity Provider client
44 cognito_client = boto3.client("cognito-idp", region_name=REGION)
45
46 # 1. Sign up the user
47 sign_up_user(cognito_client, USER_POOL_CLIENT_ID, USERNAME, PASSWORD, EMAIL)
48
49 # 2. Confirm the user (User would normally get the code via email)
50 # This part requires the code sent to the email address
51 code = input("Enter the confirmation code sent to your email: ")
52 confirm_user(cognito_client, USER_POOL_CLIENT_ID, USERNAME, code)
53
54if __name__ == "__main__":
55 main()