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

An application with Amplify libraries integrated and a minimum target of any of the following:

  • iOS 13.0, using Xcode 14.1 or later.
  • macOS 10.15, using Xcode 14.1 or later.
  • tvOS 13.0, using Xcode 14.3 or later.
  • watchOS 9.0, using Xcode 14.3 or later.
  • visionOS 1.0, using Xcode 15 beta 2 or later. (Preview support - see below for more details.)

For a full example, please follow the project setup walkthrough.

visionOS support is currently in preview and can be used by targeting the visionos-preview branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis.

For more information on how to use the visionos-preview branch, see Platform Support.

To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. In Xcode, navigate to your application target > Signing & Capabilities > + Capability, then select Keychain Sharing.

This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. See TN3137: macOS keychain APIs and implementations for more information on how Keychain works on macOS and the Keychain Sharing entitlement.

For more information on adding capabilities to your application, see Xcode Capabilities.

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.

1func signUp(username: String, password: String, email: String) async {
2 let userAttributes = [AuthUserAttribute(.email, value: email)]
3 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
4 do {
5 let signUpResult = try await Amplify.Auth.signUp(
6 username: username,
7 password: password,
8 options: options
9 )
10 if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
11 print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId))")
12 } else {
13 print("SignUp Complete")
14 }
15 } catch let error as AuthError {
16 print("An error occurred while registering a user \(error)")
17 } catch {
18 print("Unexpected error: \(error)")
19 }
20}
1func signUp(username: String, password: String, email: String) -> AnyCancellable {
2 let userAttributes = [AuthUserAttribute(.email, value: email)]
3 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
4 Amplify.Publisher.create {
5 try await Amplify.Auth.signUp(
6 username: username,
7 password: password,
8 options: options
9 )
10 }.sink {
11 if case let .failure(authError) = $0 {
12 print("An error occurred while registering a user \(authError)")
13 }
14 }
15 receiveValue: { signUpResult in
16 if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
17 print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
18 } else {
19 print("SignUp Complete")
20 }
21
22 }
23 return sink
24}

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.

1func confirmSignUp(for username: String, with confirmationCode: String) async {
2 do {
3 let confirmSignUpResult = try await Amplify.Auth.confirmSignUp(
4 for: username,
5 confirmationCode: confirmationCode
6 )
7 print("Confirm sign up result completed: \(confirmSignUpResult.isSignUpComplete)")
8 } catch let error as AuthError {
9 print("An error occurred while confirming sign up \(error)")
10 } catch {
11 print("Unexpected error: \(error)")
12 }
13}
1func confirmSignUp(for username: String, with confirmationCode: String) -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Auth.confirmSignUp(
4 for: username,
5 confirmationCode: confirmationCode
6 )
7 }.sink {
8 if case let .failure(authError) = $0 {
9 print("An error occurred while confirming sign up \(authError)")
10 }
11 }
12 receiveValue: { _ in
13 print("Confirm signUp succeeded")
14 }
15}

You will know the sign up flow is complete if you see the following in your console window:

1Confirm signUp succeeded

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:

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 if signInResult.isSignedIn {
8 print("Sign in succeeded")
9 }
10 } catch let error as AuthError {
11 print("Sign in failed \(error)")
12 } catch {
13 print("Unexpected error: \(error)")
14 }
15}
1func signIn(username: String, password: String) -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Auth.signIn(
4 username: username,
5 password: password
6 )
7 }.sink {
8 if case let .failure(authError) = $0 {
9 print("Sign in failed \(authError)")
10 }
11 }
12 receiveValue: { signInResult in
13 if signInResult.isSignedIn {
14 print("Sign in succeeded")
15 }
16 }
17}

You will know the sign in flow is complete if you see the following in your console window:

1Sign in succeeded

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.

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:

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:

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:

1func signUp(username: String, password: String, email: String, phonenumber: String) async {
2 let userAttributes = [AuthUserAttribute(.email, value: email), AuthUserAttribute(.phoneNumber, value: phonenumber)]
3 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
4
5 do {
6 let signUpResult = try await Amplify.Auth.signUp(
7 username: username,
8 password: password,
9 options: options
10 )
11
12 if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
13 print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
14 } else {
15 print("SignUp Complete")
16 }
17 } catch let error as AuthError {
18 print("An error occurred while registering a user \(error)")
19 } catch {
20 print("Unexpected error: \(error)")
21 }
22}
1func signUp(username: String, password: String, email: String, phonenumber: String) -> AnyCancellable {
2 let userAttributes = [
3 AuthUserAttribute(.email, value: email),
4 AuthUserAttribute(.phoneNumber, value: phonenumber)
5 ]
6 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
7 Amplify.Publisher.create {
8 try await Amplify.Auth.signUp(
9 username: username,
10 password: password,
11 options: options
12 )
13 }.sink {
14 if case let .failure(authError) = $0 {
15 print("An error occurred while registering a user \(authError)")
16 }
17 }
18 receiveValue: { signUpResult in
19 if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
20 print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
21 } else {
22 print("SignUp Complete")
23 }
24 }
25 return sink
26}

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.

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