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

Page updated Aug 21, 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

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

func signUpUser(
username: String,
password: String
) async throws {
var userAttributes = [
AuthUserAttribute(.email, value: "test@example.com"),
AuthUserAttribute(.phoneNumber, value: "+18885551234")
]
let options = AuthSignUpRequest.Options(
userAttributes: userAttributes)
let result = try await Amplify.Auth.signUp(
username: username,
password: password,
options: options)
print("Sign up next step: \(result.nextStep)")
}

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.

func confirmSignUpPhoneVerification(
username: String,
otpCode: String
) async throws {
let result = try await Amplify.Auth.confirmSignUp(
for: username,
confirmationCode: otpCode
)
print("Sign up complete: \(result.isSignUpComplete)")
}

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.

func signIn(username: String, password: String) async {
do {
let signInResult = try await Amplify.Auth.signIn(
username: username,
password: password
)
if case .confirmSignInWithSMSMFACode(let deliveryDetails, let info) = signInResult.nextStep {
print("SMS code send to \(deliveryDetails.destination)")
print("Additional info \(String(describing: info))")
// Prompt the user to enter the SMSMFA code they received
// Then invoke `confirmSignIn` api with the code
}
} catch let error as AuthError {
print("Sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}

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

func confirmSignIn() async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(
challengeResponse: "<confirmation code received via SMS>")
print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
} catch let error as AuthError {
print("Confirm sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}

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.

func updateMFAPreferences() async throws {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let smsMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
sms: smsMfaPreference)
}
func updateMFAPreferences() -> AnyCancellable {
Amplify.Publisher.create {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let smsMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
sms: smsMfaPreference)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: {
print("Update MFA preference succeeded")
}
}

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.

func signIn(username: String, password: String) async {
do {
let signInResult = try await Amplify.Auth.signIn(
username: username,
password: password
)
if case .continueSignInWithTOTPSetup(let setUpDetails) = signInResult.nextStep {
print("Received next step as continue sign in by setting up TOTP")
print("Shared secret that will be used to set up TOTP in the authenticator app \(setUpDetails.sharedSecret)")
// appName parameter will help distinguish the account in the Authenticator app
let setupURI = try setUpDetails.getSetupURI(appName: "<Your_App_Name>>")
print("TOTP Setup URI: \(setupURI)")
// Prompt the user to enter the TOTP code generated in their authenticator app
// Then invoke `confirmSignIn` api with the code
}
} catch let error as AuthError {
print("Sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}

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.

func confirmSignInWithTOTPSetup(totpCodeFromAuthenticatorApp: String) async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(
challengeResponse: totpCodeFromAuthenticatorApp)
if signInResult.isSignedIn {
print("Confirm sign in succeeded. The user is signed in.")
} else {
print("Confirm sign in succeeded.")
print("Next step: \(signInResult.nextStep)")
// Switch on the next step to take appropriate actions.
// If `signInResult.isSignedIn` is true, the next step
// is 'done', and the user is now signed in.
}
} catch {
print("Confirm sign in failed \(error)")
}
}

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.

func updateMFAPreferences() async throws {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let totpMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
totp: totpMfaPreference)
}
func updateMFAPreferences() -> AnyCancellable {
Amplify.Publisher.create {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let totpMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
totp: totpMfaPreference)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: {
print("Update MFA preference succeeded")
}
}

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.

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

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.

func verifyTOTPSetup(totpCodeFromAuthenticatorApp: String) async {
do {
try await Amplify.Auth.verifyTOTPSetup(
code: totpCodeFromAuthenticatorApp)
} catch {
print("TOTP Setup Verification failed \(error)")
}
}

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.

func updateMFAPreferences() async throws {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let totpMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
totp: totpMfaPreference)
}
func updateMFAPreferences() -> AnyCancellable {
Amplify.Publisher.create {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let totpMfaPreference: MFAPreference = .enabled // or .preferred
try await authCognitoPlugin?.updateMFAPreference(
totp: totpMfaPreference)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: {
print("Update MFA preference succeeded")
}
}

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.

func getMFAPreferences() async throws {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let result = try await authCognitoPlugin?.fetchMFAPreference()
print("Enabled MFA types: \(result?.enabled)")
print("Preferred MFA type: \(result?.preferred)")
}
func getMFAPreferences() -> AnyCancellable {
Amplify.Publisher.create {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
return try await authCognitoPlugin?.fetchMFAPreference()
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { (result: UserMFAPreference?) in
print("Enabled MFA types: \(result?.enabled)")
print("Preferred MFA type: \(result?.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.

func updateMFAPreferences() async throws {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let smsMfaPreference: MFAPreference = .preferred
let totpMfaPreference: MFAPreference = .enabled
try await authCognitoPlugin?.updateMFAPreference(
sms: smsMfaPreference,
totp: totpMfaPreference)
}
func updateMFAPreferences() -> AnyCancellable {
Amplify.Publisher.create {
let authCognitoPlugin = try Amplify.Auth.getPlugin(
for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
let smsMfaPreference: MFAPreference = .preferred
let totpMfaPreference: MFAPreference = .enabled
try await authCognitoPlugin?.updateMFAPreference(
sms: smsMfaPreference,
totp: totpMfaPreference)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: {
print("Update MFA preference succeeded")
}
}

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.

func confirmSignInWithTOTPAsMFASelection() async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(
challengeResponse: MFAType.totp.challengeResponse)
if case .confirmSignInWithTOTPCode = signInResult.nextStep {
print("Received next step as confirm sign in with TOTP")
}
} catch {
print("Confirm sign in failed \(error)")
}
}
func confirmSignInWithTOTPAsMFASelection() -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(
challengeResponse: MFAType.totp.challengeResponse)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
if case .confirmSignInWithTOTPCode = signInResult.nextStep {
print("Received next step as confirm sign in with TOTP")
}
}
}