Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated May 21, 2024

Manage MFA settings

Amplify Flutter v1 is now in Maintenance Mode until April 30th, 2025. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Flutter to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

The Auth category supports Multi-factor Authentication (MFA) for user sign-in flows. MFA is an extra layer of security used to make sure that users trying to gain access to an account are who they say they are. It requires users to provide additional information to verify their identity. The category supports the following MFA methods:

  • SMS
  • TOTP (Time-based One-time Password)

Set Up Backend Resources

Below are the steps you can use to set up MFA using SMS or TOTP with the Amplify CLI. The Amplify libraries are designed to work with MFA even if you have set up your Amazon Cognito resources separately.

When using Amplify CLI to set up backend resources, the following options are only available when starting a new project (via amplify add auth). You will not have access to these settings after creation (via amplify update).

  • Required MFA (i.e. Setting MFA to "ON")

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.

Refer to SMS sandbox.

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

Run amplify add auth to create a new Cognito Auth resource, and follow the prompts below depending on how you want to integrate MFA into your flow.

Turning MFA "ON" will make it required for all users, while "Optional" will make it available to enable on a per-user basis.

SMS MFA

$ amplify add auth
? Do you want to use the default authentication and security configuration?
# Manual configuration
... Answer as appropriate
? 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 {####}
... Answer as appropriate
Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

TOTP MFA

$ amplify add auth
? Do you want to use the default authentication and security configuration?
# Manual configuration
... Answer as appropriate
? Multifactor authentication (MFA) user login options:
# ON (Required for all logins, can not be enabled later)
? For user login, select the MFA types:
# Time-Based One-Time Password (TOTP)
... Answer as appropriate
Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Run amplify update auth and follow the prompts as guided below.

The following steps show how to enable MFA as "Optional" for users. In this mode, MFA must be enabled on a user-by-user basis, either through an Admin SDK (e.g. via a Lambda trigger as part of the sign-up process), or manually in the Cognito console.

If you'd like to make MFA required for users, you must first delete your auth resource by running amplify remove auth, then follow the New Project flow on this page.

SMS MFA

$ amplify update auth
? What do you want to do?
# Walkthrough all the auth configurations
... Answer as appropriate
? Multifactor authentication (MFA) user login options:
# OPTIONAL (Individual users can use MFA)
? For user login, select the MFA types:
# SMS Text Message
? Please specify an SMS authentication message:
# Your authentication code is {####}
... Answer as appropriate
Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

TOTP MFA

$ amplify update auth
? What do you want to do?
# Walkthrough all the auth configurations
... Answer as appropriate
? Multifactor authentication (MFA) user login options:
# OPTIONAL (Individual users can use MFA)
? For user login, select the MFA types:
# Time-Based One-Time Password (TOTP)
... Answer as appropriate
Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Multi-factor authentication with SMS

Enabling SMS for MFA during Sign Up

You will need to pass phone_number as a user attribute to enable SMS MFA for your users during sign up. However, if the primary login mechanism for your Cognito resource is phone_number (without enabling username), then you do not need to pass it as an attribute.

Future<void> signUpWithPhoneVerification(
String username,
String password,
) async {
await Amplify.Auth.signUp(
username: username,
password: password,
options: SignUpOptions(
userAttributes: <AuthUserAttributeKey, String>{
// ... if required
AuthUserAttributeKey.email: 'test@example.com',
AuthUserAttributeKey.phoneNumber: '+18885551234',
},
),
);
}

By default, you have to verify a user account after they sign up using the confirmSignUp API, which will send a one-time password to the user's phone number or email, depending on your Amazon Cognito configuration.

Future<void> confirmSignUpPhoneVerification(
String username,
String otpCode,
) async {
await Amplify.Auth.confirmSignUp(
username: username,
confirmationCode: otpCode,
);
}

Handling SMS MFA challenge during Sign In

After a user signs in, if they have MFA enabled for their account, a challenge will be returned that you would need to call the confirmSignIn API where the user provides their confirmation code sent to their phone number.

Future<void> signInWithPhoneVerification(
String username,
String password,
) async {
await Amplify.Auth.signIn(
username: username,
password: password,
);
}

If MFA is ON or enabled for the user, you must call confirmSignIn with the OTP sent to their phone.

Future<void> confirmSignInPhoneVerification(String otpCode) async {
await Amplify.Auth.confirmSignIn(
confirmationValue: otpCode,
);
}

After a user has been signed in, call updateMFAPreference to record the MFA type as enabled for the user and optionally set it as preferred so that subsequent logins default to using this MFA type.

Future<void> updateMfaPreferences() async {
final cognitoPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey);
await cognitoPlugin.updateMfaPreference(
sms: MfaPreference.enabled, // or .preferred
);
}

Multi-factor authentication with TOTP

You can use Time-based One-Time Password (TOTP) for multi-factor authentication (MFA) in your web or mobile applications. The Amplify Auth category includes support for TOTP setup and verification using authenticator apps, offering an integrated solution and enhanced security for your users. These apps, such as Google Authenticator, Microsoft Authenticator, have the TOTP algorithm built-in and work by using a shared secret key and the current time to generate short-lived, six digit passwords.

Setting up TOTP for a user

After you initiate a user sign in with the signIn API where a user is required to set up TOTP as an MFA method, the API call will return CONTINUE_SIGN_IN_WITH_TOTP_SETUP as a challenge and next step to handle in your app. You will get that challenge if the following conditions are met:

  • MFA is marked as Required in your user pool.
  • TOTP is enabled in your user pool.
  • User does not have TOTP MFA set up already.

The CONTINUE_SIGN_IN_WITH_TOTP_SETUP step signifies that the user must set up TOTP before they can sign in. The step returns an associated value of type TOTPSetupDetails which must be used to configure an authenticator app like Microsoft Authenticator or Google Authenticator. TOTPSetupDetails provides a helper method called getSetupURI which generates a URI that can be used, for example, in a button to open the user's installed authenticator app. For more advanced use cases, TOTPSetupDetails also contains a sharedSecret which can be used to either generate a QR code or be manually entered into an authenticator app.

Once the authenticator app is set up, the user can generate a TOTP code and provide it to the library to complete the sign in process.

Future<void> signInUser(String username, String password) async {
try {
final result = await Amplify.Auth.signIn(
username: username,
password: password,
);
return _handleSignInResult(result);
} on AuthException catch (e) {
safePrint('Error signing in: ${e.message}');
}
}
Future<void> _handleSignInResult(SignInResult result) async {
switch (result.nextStep.signInStep) {
// ···
case AuthSignInStep.continueSignInWithTotpSetup:
final totpSetupDetails = result.nextStep.totpSetupDetails!;
final setupUri = totpSetupDetails.getSetupUri(appName: 'MyApp');
safePrint('Open URI to complete setup: $setupUri');
// ···
}
}

The TOTP code can be obtained from the user via a text field or any other means. Once the user provides the TOTP code, call confirmSignIn with the TOTP code as the challengeResponse parameter.

Future<void> confirmTotpUser(String totpCode) async {
try {
final result = await Amplify.Auth.confirmSignIn(
confirmationValue: totpCode,
);
return _handleSignInResult(result);
} on AuthException catch (e) {
safePrint('Error confirming TOTP code: ${e.message}');
}
}

Enabling TOTP after a user is signed in

TOTP MFA can be set up after a user has signed in. This can be done when the following conditions are met:

  • MFA is marked as Optional or Required in your user pool.
  • TOTP is marked as an enabled MFA method in your user pool.

TOTP can be set up by calling the setUpTOTP and verifyTOTPSetup APIs in the Auth category.

Invoke the setUpTOTP API to generate a TOTPSetupDetails object which should be used to configure an Authenticator app like Microsoft Authenticator or Google Authenticator. TOTPSetupDetails provides a helper method called getSetupURI which generates a URI that can be used, for example, in a button to open the user's installed Authenticator app. For more advanced use cases, TOTPSetupDetails also contains a sharedSecret which can be used to either generate a QR code or be manually entered into an Authenticator app.

that contains the sharedSecret which will be used to either to generate a QR code or can be manually entered into an Authenticator app.

Future<void> setUpTotp() async {
try {
final totpSetupDetails = await Amplify.Auth.setUpTotp();
final setupUri = totpSetupDetails.getSetupUri(appName: 'MyApp');
safePrint('Open URI to complete setup: $setupUri');
} on AuthException catch (e) {
safePrint('An error occurred setting up TOTP: $e');
}
}

Once the Authenticator app is set up, the user must generate a TOTP code and provide it to the library. Pass the code to verifyTOTPSetup to complete the TOTP setup process.

Future<void> verifyTotpSetup(String totpCode) async {
try {
await Amplify.Auth.verifyTotpSetup(totpCode);
} on AuthException catch (e) {
safePrint('An error occurred verifying TOTP: $e');
}
}

Recovering from a lost TOTP device

If a user loses access to their TOTP device, they would need to contact an administrator to help get access to their account. Based on the Cognito user pool configuration, the administrator can use the AdminSetUserMFAPreference to either change the MFA preference to a different MFA method or to disable MFA for the user.

In a scenario where MFA is marked as Required in your user pool and another MFA method is not set up, the administrator would need to first initiate an AdminUpdateUserAttributes call and update the user’s phone number attribute. Once this is complete, the administrator can continue changing the MFA preference to SMS as suggested above.

Setting a user's preferred MFA option

Fetch the current user's MFA preferences

Invoke the following API to get the current MFA preference and enabled MFA types, if any, for the current user.

Future<void> getCurrentMfaPreference() async {
final cognitoPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey);
final currentPreference = await cognitoPlugin.fetchMfaPreference();
safePrint('Enabled MFA types for user: ${currentPreference.enabled}');
safePrint('Preferred MFA type for user: ${currentPreference.preferred}');
}

Update the current user's MFA preferences

Invoke the following API to update the MFA preference for the current user.

Only one MFA method can be marked as preferred at a time. If the user has multiple MFA methods enabled and tries to mark more than one MFA method as preferred, the API will throw an error.

Future<void> updateMfaPreferences() async {
final cognitoPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey);
await cognitoPlugin.updateMfaPreference(
sms: MfaPreference.enabled,
totp: MfaPreference.preferred,
);
}

If multiple MFA methods are enabled for the user, the signIn API will return continueSignInWithMFASelection as the next step in the auth flow. During this scenario, the user should be prompted to select the MFA method they want to use to sign in and their preference should be passed to confirmSignIn.

The MFA types which are currently supported by Amplify Auth are:

  • MfaType.sms
  • MfaType.totp
Future<void> _handleSignInResult(SignInResult result) async {
switch (result.nextStep.signInStep) {
// ···
case AuthSignInStep.continueSignInWithMfaSelection:
final allowedMfaTypes = result.nextStep.allowedMfaTypes!;
final selection = await _promptUserPreference(allowedMfaTypes);
return _handleMfaSelection(selection);
// ···
}
}
Future<MfaType> _promptUserPreference(Set<MfaType> allowedTypes) async {
// ···
}
Future<void> _handleMfaSelection(MfaType selection) async {
try {
final result = await Amplify.Auth.confirmSignIn(
confirmationValue: selection.confirmationValue,
);
return _handleSignInResult(result);
} on AuthException catch (e) {
safePrint('Error resending code: ${e.message}');
}
}