- Newest
- Most votes
- Most comments
To reproduce a flow similar to the Hosted UI using boto3 for AWS Cognito SMS MFA setup, you can follow these steps:
-
Initiate authentication: Use
initiate_authoradmin_initiate_authwith the user's login and password. This will return a session token. -
Handle MFA_SETUP challenge: If the response includes a
ChallengeNameofMFA_SETUP, you'll need to set up MFA for the user. -
Collect phone number: Prompt the user to enter their phone number.
-
Associate phone number and set up SMS MFA: Use
admin_update_user_attributesto add the phone number to the user's attributes. Then useadmin_set_user_mfa_preferenceto set SMS as the preferred MFA method. -
Restart authentication: Use
initiate_authoradmin_initiate_authagain with the user's credentials. -
Handle SMS_MFA challenge: The response should now include a
ChallengeNameofSMS_MFA. Amazon Cognito will send an SMS code to the user's phone. -
Verify code: Prompt the user to enter the code they received. Use
respond_to_auth_challengewith the challenge nameSMS_MFAand the code as the response. -
Complete authentication: If the code is correct,
respond_to_auth_challengewill return the authentication tokens.
This flow allows you to set up SMS MFA during the login process without requiring the phone number to be pre-verified. The phone number is added and the MFA method is set up before the user receives the SMS code, similar to the Hosted UI flow. The phone number is effectively verified when the user successfully enters the SMS code.
Note that this approach still adds the phone number before verification, but it closely mimics the Hosted UI flow by verifying the phone number as part of the MFA setup process. If you need to ensure the phone number is not added until after verification, you may need to implement a custom authentication flow or use AWS Lambda triggers to handle the verification process more granularly.
Sources
RespondToAuthChallenge - Amazon Cognito User Pools
AdminRespondToAuthChallenge - Amazon Cognito User Pools
InitiateAuth - Amazon Cognito User Pools
AdminInitiateAuth - Amazon Cognito User Pools
Relevant content
- asked 6 months ago
- asked 8 months ago
- AWS OFFICIALUpdated 4 months ago

Thanks for the answer.
This flow is exactly what I have at the moment. Its disadvantage is that if the user enter an incorrect phone number and I add this phone to his account and set him an SMS MFA, he will not be able to log in and it will be necessary to implement a mechanism for changing the number during the authentication process.
I didn`t use custom authentication flow before, but thanks for advice)