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

Page updated Feb 21, 2024

Multi-step sign-in

After a user has finished signup, they can proceed to sign in. Amplify Auth signin flows can be multi step processes. The required steps are determined by the configuration you provided when you ran amplify add auth. Depending on the configuration, you may need to call various APIs to finish authenticating a user's signin attempt. To identify the next step in a signin flow, inspect the nextStep parameter in the signin result.

New enumeration values

When Amplify adds a new enumeration value (e.g., a new enum class entry or sealed class subtype in Kotlin, or a new enum value in Swift/Dart/Kotlin), it will publish a new minor version of the Amplify Library. Plugins that switch over enumeration values should include default handlers (an else branch in Kotlin or a default statement in Swift/Dart/Kotlin) to ensure that they are not impacted by new enumeration values.

When called successfully, the signin APIs will return an AuthSignInResult. Inspect the nextStep property in the result to see if additional signin steps are required.

func signIn(username: String, password: String) async {
do {
let signInResult = try await Amplify.Auth.signIn(username: username, password: password)
switch signInResult.nextStep {
case .confirmSignInWithSMSMFACode(let deliveryDetails, let info):
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
case .confirmSignInWithTOTPCode:
print("Received next step as confirm sign in with TOTP code")
// Prompt the user to enter the TOTP code generated in their authenticator app
// Then invoke `confirmSignIn` api with the code
case .continueSignInWithTOTPSetup(let setUpDetails):
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)")
// Prompt the user to enter the TOTP code generated in their authenticator app
// Then invoke `confirmSignIn` api with the code
case .continueSignInWithMFASelection(let allowedMFATypes):
print("Received next step as continue sign in by selecting MFA type")
print("Allowed MFA types \(allowedMFATypes)")
// Prompt the user to select the MFA type they want to use
// Then invoke `confirmSignIn` api with the MFA type
case .confirmSignInWithCustomChallenge(let info):
print("Custom challenge, additional info \(String(describing: info))")
// Prompt the user to enter custom challenge answer
// Then invoke `confirmSignIn` api with the answer
case .confirmSignInWithNewPassword(let info):
print("New password additional info \(String(describing: info))")
// Prompt the user to enter a new password
// Then invoke `confirmSignIn` api with new password
case .resetPassword(let info):
print("Reset password additional info \(String(describing: info))")
// User needs to reset their password.
// Invoke `resetPassword` api to start the reset password
// flow, and once reset password flow completes, invoke
// `signIn` api to trigger signin flow again.
case .confirmSignUp(let info):
print("Confirm signup additional info \(String(describing: info))")
// User was not confirmed during the signup process.
// Invoke `confirmSignUp` api to confirm the user if
// they have the confirmation code. If they do not have the
// confirmation code, invoke `resendSignUpCode` to send the
// code again.
// After the user is confirmed, invoke the `signIn` api again.
case .done:
// Use has successfully signed in to the app
print("Signin complete")
}
} catch let error as AuthError{
print ("Sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}

The nextStep property is of enum type AuthSignInStep. Depending on its value, your code should take one of the following actions:

Confirm signin with SMS MFA

If the next step is confirmSignInWithSMSMFACode, Amplify Auth has sent the user a random code over SMS, and is waiting to find out if the user successfully received it. To handle this step, your app's UI must prompt the user to enter the code. After the user enters the code, your implementation must pass the value to Amplify Auth confirmSignIn API.

Note: the signin result also includes an AuthCodeDeliveryDetails member. It includes additional information about the code delivery such as the partial phone number of the SMS recipient.

func confirmSignIn(confirmationCodeFromUser: String) async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(challengeResponse: confirmationCodeFromUser)
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 let error as AuthError {
print("Confirm sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}
func confirmSignIn(confirmationCodeFromUser: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(challengeResponse: confirmationCodeFromUser)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
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.
}
}
}

Confirm signin with TOTP MFA

If the next step is confirmSignInWithTOTPCode, you should prompt the user to enter the TOTP code from their associated authenticator app during set up. The code is a six-digit number that changes every 30 seconds. The user must enter the code before the 30-second window expires.

After the user enters the code, your implementation must pass the value to Amplify Auth confirmSignIn API.

func confirmSignIn(totpCode: String) async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(challengeResponse: totpCode)
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)")
}
}
func confirmSignIn(totpCode: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(challengeResponse: totpCode)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
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.
}
}
}

Continue signin with MFA Selection

If the next step is continueSignInWithMFASelection, the user must select the MFA method to use. Amplify Auth currently only supports SMS and TOTP as MFA methods. After the user selects an MFA method, your implementation must pass the selected MFA method to Amplify Auth using confirmSignIn API.

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")
}
}
}

Continue signin with TOTP Setup

If the next step is continueSignInWithTOTPSetup, then the user must provide a TOTP code to complete the sign in process. The step returns an associated value of type TOTPSetupDetails which would be used for generating TOTP. TOTPSetupDetails provides a helper method called getSetupURI that can be used to generate a URI, which can be used by native password managers for TOTP association. For example. if the URI is used on Apple platforms, it will trigger the platform's native password manager to associate TOTP with the account. For more advanced use cases, TOTPSetupDetails also contains the sharedSecret that will be used to either generate a QR code or can 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.

// Confirm sign in with TOTP setup
case .continueSignInWithTOTPSetup(let setUpDetails):
/// 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)")
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)")
}
}
func confirmSignInWithTOTPSetup(totpCodeFromAuthenticatorApp: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(
challengeResponse: totpCodeFromAuthenticatorApp)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
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.
}
}
}

Confirm signin with custom challenge

If the next step is confirmSignInWithCustomChallenge, Amplify Auth is awaiting completion of a custom authentication challenge. The challenge is based on the Lambda trigger you setup when you configured a custom sign in flow. To complete this step, you should prompt the user for the custom challenge answer, and pass the answer to the confirmSignIn API.

func confirmSignIn(challengeAnswerFromUser: String) async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(challengeResponse: challengeAnswerFromUser)
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 let error as AuthError {
print("Confirm sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}
func confirmSignIn(challengeAnswerFromUser: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(challengeResponse: challengeAnswerFromUser)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
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.
}
}
}
Special Handling on ConfirmSignIn

During a confirmSignIn call if failAuthentication=true is returned by the lambda the session of the request gets invalidated by cognito, a NotAuthorizedException is returned and a new signIn call is expected via Amplify.Auth.signIn

Exception: notAuthorized{message=Failed since user is not authorized., cause=NotAuthorizedException(message=Invalid session for the user.), recoverySuggestion=Check whether the given values are correct and the user is authorized to perform the operation.}

Confirm signin with new password

If the next step is confirmSignInWithNewPassword, Amplify Auth requires a new password for the user before they can proceed. Prompt the user for a new password and pass it to the confirmSignIn API.

func confirmSignIn(newPasswordFromUser: String) async {
do {
let signInResult = try await Amplify.Auth.confirmSignIn(challengeResponse: newPasswordFromUser)
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 let error as AuthError {
print("Confirm sign in failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}
func confirmSignIn(newPasswordFromUser: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignIn(challengeResponse: newPasswordFromUser)
}.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
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.
}
}
}

Reset password

If you receive resetPassword, authentication flow could not proceed without resetting the password. The next step is to invoke resetPassword api and follow the reset password flow.

func resetPassword(username: String) async {
do {
let resetPasswordResult = try await Amplify.Auth.resetPassword(for: username)
print("Reset password succeeded.")
print("Next step: \(resetPasswordResult.nextStep)")
} catch let error as AuthError {
print("Reset password failed \(error)")
} catch {
print("Unexpected error: \(error)")
}
}
func resetPassword(username: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.resetPassword(for: username)
}.sink {
if case let .failure(authError) = $0 {
print("Reset password failed \(authError)")
}
}
receiveValue: { resetPasswordResult in
print("Reset password succeeded.")
print("Next step: \(resetPasswordResult.nextStep)")
}
}

Confirm Signup

If you receive confirmSignUp as a next step, sign up could not proceed without confirming user information such as email or phone number. The next step is to invoke the confirmSignUp API and follow the confirm signup flow.

func confirmSignUp(for username: String, with confirmationCode: String) async {
do {
let confirmSignUpResult = try await Amplify.Auth.confirmSignUp(
for: username,
confirmationCode: confirmationCode
)
print("Confirm sign up result completed: \(confirmSignUpResult.isSignUpComplete)")
} catch let error as AuthError {
print("An error occurred while confirming sign up \(error)")
} catch {
print("Unexpected error: \(error)")
}
}
func confirmSignUp(for username: String, with confirmationCode: String) -> AnyCancellable {
Amplify.Publisher.create {
try await Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode)
}.sink {
if case let .failure(authError) = $0 {
print("An error occurred while confirming sign up \(authError)")
}
}
receiveValue: { _ in
print("Confirm signUp succeeded")
}
}

Done

Signin flow is complete when you get done. This means the user is successfully authenticated. As a convenience, the SignInResult also provides the isSignedIn property, which will be true if the next step is done.