Enable sign-in
The Auth category can be used to register a user, confirm attributes like email/phone, and sign in with optional multi-factor authentication. It is set up to use Amazon Cognito User Pools which manages the users and their properties.
Prerequisites
- An app setup according to the getting started walkthrough
Register a user
The default CLI flow as mentioned in the getting started guide requires a username, password and a valid email id as parameters to register a user. Invoke the following api to initiate a sign up flow.
/// Signs a user up with a username, password, and email. The required/// attributes may be different depending on your app's configuration.Future<void> signUpUser({ required String username, required String password, required String email, String? phoneNumber,}) async { try { final userAttributes = { AuthUserAttributeKey.email: email, if (phoneNumber != null) AuthUserAttributeKey.phoneNumber: phoneNumber, // additional attributes as needed }; final result = await Amplify.Auth.signUp( username: username, password: password, options: SignUpOptions( userAttributes: userAttributes, ), ); await _handleSignUpResult(result); } on AuthException catch (e) { safePrint('Error signing up user: ${e.message}'); }}
Future<void> _handleSignUpResult(SignUpResult result) async { switch (result.nextStep.signUpStep) { case AuthSignUpStep.confirmSignUp: final codeDeliveryDetails = result.nextStep.codeDeliveryDetails!; _handleCodeDelivery(codeDeliveryDetails); break; case AuthSignUpStep.done: safePrint('Sign up is complete'); break; }}
void _handleCodeDelivery(AuthCodeDeliveryDetails codeDeliveryDetails) { safePrint( 'A confirmation code has been sent to ${codeDeliveryDetails.destination}. ' 'Please check your ${codeDeliveryDetails.deliveryMedium.name} for the code.', );}
The next step in the sign up flow is to confirm the user. A confirmation code will be sent to the email id provided during sign up. Enter the confirmation code received via email in the confirmSignUp
call.
Future<void> confirmUser({ required String username, required String confirmationCode,}) async { try { final result = await Amplify.Auth.confirmSignUp( username: username, confirmationCode: confirmationCode, ); // Check if further confirmations are needed or if // the sign up is complete. await _handleSignUpResult(result); } on AuthException catch (e) { safePrint('Error confirming user: ${e.message}'); }}
Sign in a user
Implement a UI to get the username and password from the user. After the user enters the username and password you can start the sign in flow by calling the following method:
Future<void> signInUser(String username, String password) async { try { final result = await Amplify.Auth.signIn( username: username, password: password, ); await _handleSignInResult(result); } on AuthException catch (e) { safePrint('Error signing in: ${e.message}'); }}
Depending on your configuration and how the user signed up, one or more confirmations will be necessary.
Use the SignInResult
returned from Amplify.Auth.signIn
to check the next step for signing in. When
the value is done
, the user has successfully signed in.
Future<void> _handleSignInResult(SignInResult result) async { switch (result.nextStep.signInStep) { case AuthSignInStep.confirmSignInWithSmsMfaCode: final codeDeliveryDetails = result.nextStep.codeDeliveryDetails!; _handleCodeDelivery(codeDeliveryDetails); break; case AuthSignInStep.confirmSignInWithNewPassword: safePrint('Enter a new password to continue signing in'); break; case AuthSignInStep.confirmSignInWithCustomChallenge: final parameters = result.nextStep.additionalInfo; final prompt = parameters['prompt']!; safePrint(prompt); break; case AuthSignInStep.resetPassword: final resetResult = await Amplify.Auth.resetPassword( username: username, ); await _handleResetPasswordResult(resetResult); break; case AuthSignInStep.confirmSignUp: // Resend the sign up code to the registered device. final resendResult = await Amplify.Auth.resendSignUpCode( username: username, ); _handleCodeDelivery(resendResult.codeDeliveryDetails); break; case AuthSignInStep.done: safePrint('Sign in is complete'); break; }}
void _handleCodeDelivery(AuthCodeDeliveryDetails codeDeliveryDetails) { safePrint( 'A confirmation code has been sent to ${codeDeliveryDetails.destination}. ' 'Please check your ${codeDeliveryDetails.deliveryMedium.name} for the code.', );}
You have now successfully registered a user and authenticated with that user's username and password with Amplify. The Authentication category supports other mechanisms for authentication such as web UI based sign in, sign in using other providers etc that you can explore in the other sections.
Switching authentication flow at runtime
By default, the authenticationFlowType
value specified in your amplifyconfiguration.dart
will be used when authenticating with Cognito. You can change the default behavior at runtime with CognitoSignInPluginOptions
:
Future<void> signInCustom(String username, String password) async { try { final result = await Amplify.Auth.signIn( username: username, password: password, options: const SignInOptions( pluginOptions: CognitoSignInPluginOptions( authFlowType: AuthenticationFlowType.customAuthWithSrp, ), ), ); await _handleSignInResult(result); } on AuthException catch (e) { safePrint('Error signing in: ${e.message}'); }}
You can learn more about the custom auth flow here.
Multi-factor authentication
Some steps in setting up multi-factor authentication can only be chosen during the initial setup of Auth. If you have already added Auth via the CLI, navigate to your project directory in Terminal, run amplify auth remove
and when that completes, amplify push
to remove it.
Now, run amplify add auth
and setup Auth with the following options:
? Do you want to use the default authentication and security configuration? `Manual configuration`? Select the authentication/authorization services that you want to use: `User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)`? Please provide a friendly name for your resource that will be used to label this category in the project: `<default>`? Please enter a name for your identity pool. `<default>`? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) `Yes`? Do you want to enable 3rd party authentication providers in your identity pool? `No`? Please provide a name for your user pool: `<default>`Warning: you will not be able to edit these selections.? How do you want users to be able to sign in? `Username`? Do you want to add User Pool Groups? `No`? Do you want to add an admin queries API? `No`? Multifactor authentication (MFA) user login options: `ON (Required for all logins, can not be enabled later)`? For user login, select the MFA types: `SMS Text Message`? Please specify an SMS authentication message: `Your authentication code is {####}`? Email based user registration/forgot password: `Enabled (Requires per-user email entry at registration)`? Please specify an email verification subject: `Your verification code`? Please specify an email verification message: `Your verification code is {####}`? Do you want to override the default password policy for this User Pool? `No`Warning: you will not be able to edit these selections.? What attributes are required for signing up? `Email, Phone Number (This attribute is not supported by Facebook, Login With Amazon.)`? Specify the app's refresh token expiration period (in days): `30`? Do you want to specify the user attributes this app can read and write? `No`? Do you want to enable any of the following capabilities? `NA`? Do you want to use an OAuth flow? `No`? Do you want to configure Lambda Triggers for Cognito? `No`
To push your changes to the cloud, execute the command:
amplify push
In order to send SMS authentication codes, you must request an origination number. Authentication codes will be sent from the origination number. If your AWS account is in the SMS sandbox, you must also add a destination phone number, which can be done by going to the Amazon Pinpoint Console, selecting SMS and voice in the navigation pane, and selecting Add phone number in the Destination phone numbers tab. To check if your AWS account is in the SMS sandbox, go to the SNS console, select the Text messaging (SMS) tab from the navigation pane, and check the status under the Account information section.
When you sign up, be sure to include both email and phone attributes with the phone number formatted as follows:
Future<void> setUpMFASignUp() async { try { final userAttributes = <AuthUserAttributeKey, String>{ AuthUserAttributeKey.email: 'email@domain.com', // Note: phone_number requires country code AuthUserAttributeKey.phoneNumber: '+15559101234', }; final result = await Amplify.Auth.signUp( username: 'myusername', password: 'mysupersecurepassword', options: SignUpOptions(userAttributes: userAttributes), ); await _handleSignUpResult(result); } on AuthException catch (e) { safePrint('Error signing up: ${e.message}'); }}
You'll then confirm signup, sign in, and get back a nextStep in the sign in result of type CONFIRM_SIGN_IN_WITH_SMS_MFA_CODE
. A confirmation code will also be texted to the phone number provided above. Pass the code you received to the confirmSignIn api:
Future<void> confirmMFAUser() async { try { final result = await Amplify.Auth.confirmSignIn( confirmationValue: '123456', ); await _handleSignInResult(result); } on AuthException catch (e) { safePrint('Error confirming sign in: ${e.message}'); }}