Page updated Feb 29, 2024

Manage MFA settings

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

1$ amplify add auth
2
3? Do you want to use the default authentication and security configuration?
4# Manual configuration
5
6... Answer as appropriate
7
8? Multifactor authentication (MFA) user login options:
9# ON (Required for all logins, can not be enabled later)
10? For user login, select the MFA types:
11# SMS Text Message
12? Please specify an SMS authentication message:
13# Your authentication code is {####}
14
15... Answer as appropriate
16
17Some next steps:
18"amplify push" will build all your local backend resources and provision it in the cloud
19"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

1$ amplify add auth
2
3? Do you want to use the default authentication and security configuration?
4# Manual configuration
5
6... Answer as appropriate
7
8? Multifactor authentication (MFA) user login options:
9# ON (Required for all logins, can not be enabled later)
10? For user login, select the MFA types:
11# Time-Based One-Time Password (TOTP)
12
13... Answer as appropriate
14
15Some next steps:
16"amplify push" will build all your local backend resources and provision it in the cloud
17"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

1$ amplify update auth
2
3? What do you want to do?
4# Walkthrough all the auth configurations
5
6... Answer as appropriate
7
8? Multifactor authentication (MFA) user login options:
9# OPTIONAL (Individual users can use MFA)
10? For user login, select the MFA types:
11# SMS Text Message
12? Please specify an SMS authentication message:
13# Your authentication code is {####}
14
15... Answer as appropriate
16
17Some next steps:
18"amplify push" will build all your local backend resources and provision it in the cloud
19"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

1$ amplify update auth
2
3? What do you want to do?
4# Walkthrough all the auth configurations
5
6... Answer as appropriate
7
8? Multifactor authentication (MFA) user login options:
9# OPTIONAL (Individual users can use MFA)
10? For user login, select the MFA types:
11# Time-Based One-Time Password (TOTP)
12
13... Answer as appropriate
14
15Some next steps:
16"amplify push" will build all your local backend resources and provision it in the cloud
17"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.

1func signUpUser(
2 username: String,
3 password: String
4) async throws {
5
6 var userAttributes = [
7 AuthUserAttribute(.email, value: "test@example.com"),
8 AuthUserAttribute(.phoneNumber, value: "+18885551234")
9 ]
10
11 let options = AuthSignUpRequest.Options(
12 userAttributes: userAttributes)
13 let result = try await Amplify.Auth.signUp(
14 username: username,
15 password: password,
16 options: options)
17
18 print("Sign up next step: \(result.nextStep)")
19}

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.

1func confirmSignUpPhoneVerification(
2 username: String,
3 otpCode: String
4) async throws {
5
6 let result = try await Amplify.Auth.confirmSignUp(
7 for: username,
8 confirmationCode: otpCode
9 )
10
11 print("Sign up complete: \(result.isSignUpComplete)")
12}

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.

1func signIn(username: String, password: String) async {
2 do {
3 let signInResult = try await Amplify.Auth.signIn(
4 username: username,
5 password: password
6 )
7
8 if case .confirmSignInWithSMSMFACode(let deliveryDetails, let info) = signInResult.nextStep {
9 print("SMS code send to \(deliveryDetails.destination)")
10 print("Additional info \(String(describing: info))")
11
12 // Prompt the user to enter the SMSMFA code they received
13 // Then invoke `confirmSignIn` api with the code
14 }
15 } catch let error as AuthError {
16 print("Sign in failed \(error)")
17 } catch {
18 print("Unexpected error: \(error)")
19 }
20}

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

1func confirmSignIn() async {
2 do {
3 let signInResult = try await Amplify.Auth.confirmSignIn(
4 challengeResponse: "<confirmation code received via SMS>")
5 print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
6 } catch let error as AuthError {
7 print("Confirm sign in failed \(error)")
8 } catch {
9 print("Unexpected error: \(error)")
10 }
11}

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.

1func updateMFAPreferences() async throws {
2 let authCognitoPlugin = try Amplify.Auth.getPlugin(
3 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
4
5 let smsMfaPreference: MFAPreference = .enabled // or .preferred
6
7 try await authCognitoPlugin?.updateMFAPreference(
8 sms: smsMfaPreference)
9}
1func updateMFAPreferences() -> AnyCancellable {
2 Amplify.Publisher.create {
3 let authCognitoPlugin = try Amplify.Auth.getPlugin(
4 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
5
6 let smsMfaPreference: MFAPreference = .enabled // or .preferred
7
8 try await authCognitoPlugin?.updateMFAPreference(
9 sms: smsMfaPreference)
10 }.sink {
11 if case let .failure(authError) = $0 {
12 print("Confirm sign in failed \(authError)")
13 }
14 }
15 receiveValue: {
16 print("Update MFA preference succeeded")
17 }
18}

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 continueSignInWithTOTPSetup 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 Cognito User Pool.
  • TOTP is enabled in the Cognito User Pool
  • User does not have TOTP MFA set up already.

The continueSignInWithTOTPSetup 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.

1func signIn(username: String, password: String) async {
2 do {
3 let signInResult = try await Amplify.Auth.signIn(
4 username: username,
5 password: password
6 )
7
8 if case .continueSignInWithTOTPSetup(let setUpDetails) = signInResult.nextStep {
9
10 print("Received next step as continue sign in by setting up TOTP")
11 print("Shared secret that will be used to set up TOTP in the authenticator app \(setUpDetails.sharedSecret)")
12
13 // appName parameter will help distinguish the account in the Authenticator app
14 let setupURI = try setUpDetails.getSetupURI(appName: "<Your_App_Name>>")
15
16 print("TOTP Setup URI: \(setupURI)")
17
18 // Prompt the user to enter the TOTP code generated in their authenticator app
19 // Then invoke `confirmSignIn` api with the code
20
21 }
22 } catch let error as AuthError {
23 print("Sign in failed \(error)")
24 } catch {
25 print("Unexpected error: \(error)")
26 }
27}

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.

1func confirmSignInWithTOTPSetup(totpCodeFromAuthenticatorApp: String) async {
2 do {
3 let signInResult = try await Amplify.Auth.confirmSignIn(
4 challengeResponse: totpCodeFromAuthenticatorApp)
5
6 if signInResult.isSignedIn {
7 print("Confirm sign in succeeded. The user is signed in.")
8 } else {
9 print("Confirm sign in succeeded.")
10 print("Next step: \(signInResult.nextStep)")
11 // Switch on the next step to take appropriate actions.
12 // If `signInResult.isSignedIn` is true, the next step
13 // is 'done', and the user is now signed in.
14 }
15 } catch {
16 print("Confirm sign in failed \(error)")
17 }
18}

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.

1func updateMFAPreferences() async throws {
2 let authCognitoPlugin = try Amplify.Auth.getPlugin(
3 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
4
5 let totpMfaPreference: MFAPreference = .enabled // or .preferred
6
7 try await authCognitoPlugin?.updateMFAPreference(
8 totp: totpMfaPreference)
9}
1func updateMFAPreferences() -> AnyCancellable {
2 Amplify.Publisher.create {
3 let authCognitoPlugin = try Amplify.Auth.getPlugin(
4 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
5
6 let totpMfaPreference: MFAPreference = .enabled // or .preferred
7
8 try await authCognitoPlugin?.updateMFAPreference(
9 totp: totpMfaPreference)
10 }.sink {
11 if case let .failure(authError) = $0 {
12 print("Confirm sign in failed \(authError)")
13 }
14 }
15 receiveValue: {
16 print("Update MFA preference succeeded")
17 }
18}

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 the Cognito User Pool
  • TOTP is marked as an enabled MFA method in Cognito 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.

1func setUpTOTP() async {
2 do {
3 let setUpDetails = try await Amplify.Auth.setUpTOTP()
4
5 print("Received next step as continue sign in by setting up TOTP")
6 print("Shared secret that will be used to set up TOTP in the authenticator app \(setUpDetails.sharedSecret)")
7
8 // appName parameter will help distinguish the account in the Authenticator app
9 let setupURI = try setUpDetails.getSetupURI(appName: "<Your_App_Name>>")
10
11 print("TOTP Setup URI: \(setupURI)")
12
13 // Prompt the user to enter the TOTP code generated in their authenticator app
14 // Then invoke `confirmSignIn` api with the code
15 } catch {
16 print("TOTP Setup Initiation failed \(error)")
17 }
18}

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.

1func verifyTOTPSetup(totpCodeFromAuthenticatorApp: String) async {
2 do {
3 try await Amplify.Auth.verifyTOTPSetup(
4 code: totpCodeFromAuthenticatorApp)
5 } catch {
6 print("TOTP Setup Verification failed \(error)")
7 }
8}

After TOTP setup is complete, 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.

1func updateMFAPreferences() async throws {
2 let authCognitoPlugin = try Amplify.Auth.getPlugin(
3 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
4
5 let totpMfaPreference: MFAPreference = .enabled // or .preferred
6
7 try await authCognitoPlugin?.updateMFAPreference(
8 totp: totpMfaPreference)
9}
1func updateMFAPreferences() -> AnyCancellable {
2 Amplify.Publisher.create {
3 let authCognitoPlugin = try Amplify.Auth.getPlugin(
4 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
5
6 let totpMfaPreference: MFAPreference = .enabled // or .preferred
7
8 try await authCognitoPlugin?.updateMFAPreference(
9 totp: totpMfaPreference)
10 }.sink {
11 if case let .failure(authError) = $0 {
12 print("Confirm sign in failed \(authError)")
13 }
14 }
15 receiveValue: {
16 print("Update MFA preference succeeded")
17 }
18}

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 Cognito 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.

1func getMFAPreferences() async throws {
2 let authCognitoPlugin = try Amplify.Auth.getPlugin(
3 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
4
5 let result = try await authCognitoPlugin?.fetchMFAPreference()
6
7 print("Enabled MFA types: \(result?.enabled)")
8 print("Preferred MFA type: \(result?.preferred)")
9}
1func getMFAPreferences() -> AnyCancellable {
2 Amplify.Publisher.create {
3 let authCognitoPlugin = try Amplify.Auth.getPlugin(
4 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
5 return try await authCognitoPlugin?.fetchMFAPreference()
6 }.sink {
7 if case let .failure(authError) = $0 {
8 print("Confirm sign in failed \(authError)")
9 }
10 }
11 receiveValue: { (result: UserMFAPreference?) in
12 print("Enabled MFA types: \(result?.enabled)")
13 print("Preferred MFA type: \(result?.preferred)")
14 }
15}

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.

1func updateMFAPreferences() async throws {
2 let authCognitoPlugin = try Amplify.Auth.getPlugin(
3 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
4
5 let smsMfaPreference: MFAPreference = .preferred
6 let totpMfaPreference: MFAPreference = .enabled
7
8 try await authCognitoPlugin?.updateMFAPreference(
9 sms: smsMfaPreference,
10 totp: totpMfaPreference)
11}
1func updateMFAPreferences() -> AnyCancellable {
2 Amplify.Publisher.create {
3 let authCognitoPlugin = try Amplify.Auth.getPlugin(
4 for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
5
6 let smsMfaPreference: MFAPreference = .preferred
7 let totpMfaPreference: MFAPreference = .enabled
8
9 try await authCognitoPlugin?.updateMFAPreference(
10 sms: smsMfaPreference,
11 totp: totpMfaPreference)
12 }.sink {
13 if case let .failure(authError) = $0 {
14 print("Confirm sign in failed \(authError)")
15 }
16 }
17 receiveValue: {
18 print("Update MFA preference succeeded")
19 }
20}

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.

1func confirmSignInWithTOTPAsMFASelection() async {
2 do {
3 let signInResult = try await Amplify.Auth.confirmSignIn(
4 challengeResponse: MFAType.totp.challengeResponse)
5
6 if case .confirmSignInWithTOTPCode = signInResult.nextStep {
7 print("Received next step as confirm sign in with TOTP")
8 }
9
10 } catch {
11 print("Confirm sign in failed \(error)")
12 }
13}
1func confirmSignInWithTOTPAsMFASelection() -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Auth.confirmSignIn(
4 challengeResponse: MFAType.totp.challengeResponse)
5 }.sink {
6 if case let .failure(authError) = $0 {
7 print("Confirm sign in failed \(authError)")
8 }
9 }
10 receiveValue: { signInResult in
11 if case .confirmSignInWithTOTPCode = signInResult.nextStep {
12 print("Received next step as confirm sign in with TOTP")
13 }
14 }
15}