Page updated Nov 3, 2023

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

When configuring Social sign-in through the Amplify CLI, it's important to exercise caution when designating attributes as "required." Different social identity providers have varied scopes in terms of the information they respond back to Cognito with. User pool attributes that are initially set up as "required" cannot be changed later, and may require you to migrate the users or create a new user pool.

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}'); } }
1/// Signs a user up with a username, password, and email. The required
2/// attributes may be different depending on your app's configuration.
3Future<void> signUpUser({
4 required String username,
5 required String password,
6 required String email,
7 String? phoneNumber,
8}) async {
9 try {
10 final userAttributes = {
11 AuthUserAttributeKey.email: email,
12 if (phoneNumber != null) AuthUserAttributeKey.phoneNumber: phoneNumber,
13 // additional attributes as needed
14 };
15 final result = await Amplify.Auth.signUp(
16 username: username,
17 password: password,
18 options: SignUpOptions(
19 userAttributes: userAttributes,
20 ),
21 );
22 await _handleSignUpResult(result);
23 } on AuthException catch (e) {
24 safePrint('Error signing up user: ${e.message}');
25 }
26}
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.', ); }
1Future<void> _handleSignUpResult(SignUpResult result) async {
2 switch (result.nextStep.signUpStep) {
3 case AuthSignUpStep.confirmSignUp:
4 final codeDeliveryDetails = result.nextStep.codeDeliveryDetails!;
5 _handleCodeDelivery(codeDeliveryDetails);
6 break;
7 case AuthSignUpStep.done:
8 safePrint('Sign up is complete');
9 break;
10 }
11}
12
13void _handleCodeDelivery(AuthCodeDeliveryDetails codeDeliveryDetails) {
14 safePrint(
15 'A confirmation code has been sent to ${codeDeliveryDetails.destination}. '
16 'Please check your ${codeDeliveryDetails.deliveryMedium.name} for the code.',
17 );
18}

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}'); } }
1Future<void> confirmUser({
2 required String username,
3 required String confirmationCode,
4}) async {
5 try {
6 final result = await Amplify.Auth.confirmSignUp(
7 username: username,
8 confirmationCode: confirmationCode,
9 );
10 // Check if further confirmations are needed or if
11 // the sign up is complete.
12 await _handleSignUpResult(result);
13 } on AuthException catch (e) {
14 safePrint('Error confirming user: ${e.message}');
15 }
16}

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:

Please note that you will be prevented from successfully calling signIn if a user has already signed in and a valid session is active. You must first call signOut to remove the original session.

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}'); } }
1Future<void> signInUser(String username, String password) async {
2 try {
3 final result = await Amplify.Auth.signIn(
4 username: username,
5 password: password,
6 );
7 await _handleSignInResult(result);
8 } on AuthException catch (e) {
9 safePrint('Error signing in: ${e.message}');
10 }
11}

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.', ); }
1Future<void> _handleSignInResult(SignInResult result) async {
2 switch (result.nextStep.signInStep) {
3 case AuthSignInStep.confirmSignInWithSmsMfaCode:
4 final codeDeliveryDetails = result.nextStep.codeDeliveryDetails!;
5 _handleCodeDelivery(codeDeliveryDetails);
6 break;
7 case AuthSignInStep.confirmSignInWithNewPassword:
8 safePrint('Enter a new password to continue signing in');
9 break;
10 case AuthSignInStep.confirmSignInWithCustomChallenge:
11 final parameters = result.nextStep.additionalInfo;
12 final prompt = parameters['prompt']!;
13 safePrint(prompt);
14 break;
15 case AuthSignInStep.resetPassword:
16 final resetResult = await Amplify.Auth.resetPassword(
17 username: username,
18 );
19 await _handleResetPasswordResult(resetResult);
20 break;
21 case AuthSignInStep.confirmSignUp:
22 // Resend the sign up code to the registered device.
23 final resendResult = await Amplify.Auth.resendSignUpCode(
24 username: username,
25 );
26 _handleCodeDelivery(resendResult.codeDeliveryDetails);
27 break;
28 case AuthSignInStep.done:
29 safePrint('Sign in is complete');
30 break;
31 }
32}
33
34void _handleCodeDelivery(AuthCodeDeliveryDetails codeDeliveryDetails) {
35 safePrint(
36 'A confirmation code has been sent to ${codeDeliveryDetails.destination}. '
37 'Please check your ${codeDeliveryDetails.deliveryMedium.name} for the code.',
38 );
39}

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}'); } }
1Future<void> signInCustom(String username, String password) async {
2 try {
3 final result = await Amplify.Auth.signIn(
4 username: username,
5 password: password,
6 options: const SignInOptions(
7 pluginOptions: CognitoSignInPluginOptions(
8 authFlowType: AuthenticationFlowType.customAuthWithSrp,
9 ),
10 ),
11 );
12 await _handleSignInResult(result);
13 } on AuthException catch (e) {
14 safePrint('Error signing in: ${e.message}');
15 }
16}

You can learn more about the custom auth flow here.

Multi-factor authentication

Note: If you create or update an SMS MFA configuration for your Cognito user pool, the Cognito service will send a test SMS message to an internal number in order to verify your configuration. You will be charged for these test messages by Amazon SNS.

For information about Amazon SNS pricing, see Worldwide SMS Pricing.

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`
1? Do you want to use the default authentication and security configuration?
2 `Manual configuration`
3? Select the authentication/authorization services that you want to use:
4 `User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)`
5? Please provide a friendly name for your resource that will be used to label this category in the project:
6 `<default>`
7? Please enter a name for your identity pool.
8 `<default>`
9? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM)
10 `Yes`
11? Do you want to enable 3rd party authentication providers in your identity pool?
12 `No`
13? Please provide a name for your user pool:
14 `<default>`
15Warning: you will not be able to edit these selections.
16? How do you want users to be able to sign in?
17 `Username`
18? Do you want to add User Pool Groups?
19 `No`
20? Do you want to add an admin queries API?
21 `No`
22? Multifactor authentication (MFA) user login options:
23 `ON (Required for all logins, can not be enabled later)`
24? For user login, select the MFA types:
25 `SMS Text Message`
26? Please specify an SMS authentication message:
27 `Your authentication code is {####}`
28? Email based user registration/forgot password:
29 `Enabled (Requires per-user email entry at registration)`
30? Please specify an email verification subject:
31 `Your verification code`
32? Please specify an email verification message:
33 `Your verification code is {####}`
34? Do you want to override the default password policy for this User Pool?
35 `No`
36Warning: you will not be able to edit these selections.
37? What attributes are required for signing up?
38 `Email, Phone Number (This attribute is not supported by Facebook, Login With Amazon.)`
39? Specify the app's refresh token expiration period (in days):
40 `30`
41? Do you want to specify the user attributes this app can read and write?
42 `No`
43? Do you want to enable any of the following capabilities?
44 `NA`
45? Do you want to use an OAuth flow?
46 `No`
47? Do you want to configure Lambda Triggers for Cognito?
48 `No`

To push your changes to the cloud, execute the command:

amplify push
1amplify 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}'); } }
1Future<void> setUpMFASignUp() async {
2 try {
3 final userAttributes = <AuthUserAttributeKey, String>{
4 AuthUserAttributeKey.email: 'email@domain.com',
5 // Note: phone_number requires country code
6 AuthUserAttributeKey.phoneNumber: '+15559101234',
7 };
8 final result = await Amplify.Auth.signUp(
9 username: 'myusername',
10 password: 'mysupersecurepassword',
11 options: SignUpOptions(userAttributes: userAttributes),
12 );
13 await _handleSignUpResult(result);
14 } on AuthException catch (e) {
15 safePrint('Error signing up: ${e.message}');
16 }
17}

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:

Note that you must call confirmSignIn in the same app session as you call signIn. If you close the app, you'll need to call signIn again. As a result, for testing purposes, you'll at least need an input field where you can enter the code sent via SMS and feed it to confirmSignIn.

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}'); } }
1Future<void> confirmMFAUser() async {
2 try {
3 final result = await Amplify.Auth.confirmSignIn(
4 confirmationValue: '123456',
5 );
6 await _handleSignInResult(result);
7 } on AuthException catch (e) {
8 safePrint('Error confirming sign in: ${e.message}');
9 }
10}