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

Enable sign-in

Amplify iOS v1 is deprecated as of June 1st, 2024. No new features or bug fixes will be added. Dependencies may become outdated and potentially introduce compatibility issues.

Please use the latest version (v2) of Amplify Library for Swift to get started. Refer to the upgrade guide for instructions on upgrading your application to the latest version.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

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 iOS application targeting at least iOS 11.0 with Amplify libraries integrated

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.

func signUp(username: String, password: String, email: String) {
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
Amplify.Auth.signUp(username: username, password: password, options: options) { result in
switch result {
case .success(let signUpResult):
if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
print("Delivery details \(String(describing: deliveryDetails))")
} else {
print("SignUp Complete")
}
case .failure(let error):
print("An error occurred while registering a user \(error)")
}
}
}
func signUp(username: String, password: String, email: String) -> AnyCancellable {
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
let sink = Amplify.Auth.signUp(username: username, password: password, options: options)
.resultPublisher
.sink {
if case let .failure(authError) = $0 {
print("An error occurred while registering a user \(authError)")
}
}
receiveValue: { signUpResult in
if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
print("Delivery details \(String(describing: deliveryDetails))")
} else {
print("SignUp Complete")
}
}
return sink
}

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.

func confirmSignUp(for username: String, with confirmationCode: String) {
Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode) { result in
switch result {
case .success:
print("Confirm signUp succeeded")
case .failure(let error):
print("An error occurred while confirming sign up \(error)")
}
}
}
func confirmSignUp(for username: String, with confirmationCode: String) -> AnyCancellable {
Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode)
.resultPublisher
.sink {
if case let .failure(authError) = $0 {
print("An error occurred while confirming sign up \(authError)")
}
}
receiveValue: { _ in
print("Confirm signUp succeeded")
}
}

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

Confirm 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:

func signIn(username: String, password: String) {
Amplify.Auth.signIn(username: username, password: password) { result in
switch result {
case .success:
print("Sign in succeeded")
case .failure(let error):
print("Sign in failed \(error)")
}
}
}
func signIn(username: String, password: String) -> AnyCancellable {
Amplify.Auth.signIn(username: username, password: password)
.resultPublisher
.sink {
if case let .failure(authError) = $0 {
print("Sign in failed \(authError)")
}
}
receiveValue: { _ in
print("Sign in succeeded")
}
}

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

Sign 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:

? Do you want to use the default authentication and security configuration?
`Manual configuration`
? Select the authentication/authorization services that you want to use:
`User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)`
? Please provide a friendly name for your resource that will be used to label this category in the project:
`<default>`
? Please enter a name for your identity pool.
`<default>`
? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM)
`Yes`
? Do you want to enable 3rd party authentication providers in your identity pool?
`No`
? Please provide a name for your user pool:
`<default>`
Warning: you will not be able to edit these selections.
? How do you want users to be able to sign in?
`Username`
? Do you want to add User Pool Groups?
`No`
? Do you want to add an admin queries API?
`No`
? 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 {####}`
? Email based user registration/forgot password:
`Enabled (Requires per-user email entry at registration)`
? Please specify an email verification subject:
`Your verification code`
? Please specify an email verification message:
`Your verification code is {####}`
? Do you want to override the default password policy for this User Pool?
`No`
Warning: you will not be able to edit these selections.
? What attributes are required for signing up?
`Email, Phone Number (This attribute is not supported by Facebook, Login With Amazon.)`
? Specify the app's refresh token expiration period (in days):
`30`
? Do you want to specify the user attributes this app can read and write?
`No`
? Do you want to enable any of the following capabilities?
`NA`
? Do you want to use an OAuth flow?
`No`
? Do you want to configure Lambda Triggers for Cognito?
`No`

To push your changes to the cloud, execute the command:

amplify 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:

func signUp(username: String, password: String, email: String, phonenumber: String) {
let userAttributes = [AuthUserAttribute(.email, value: email), AuthUserAttribute(.phoneNumber, value: phonenumber)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
Amplify.Auth.signUp(username: username, password: password, options: options) { result in
switch result {
case .success(let signUpResult):
if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
print("Delivery details \(String(describing: deliveryDetails))")
} else {
print("SignUp Complete")
}
case .failure(let error):
print("An error occurred while registering a user \(error)")
}
}
}
func signUp(username: String, password: String, email: String, phonenumber: String) -> AnyCancellable {
let userAttributes = [AuthUserAttribute(.email, value: email), AuthUserAttribute(.phoneNumber, value: phonenumber)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
let sink = Amplify.Auth.signUp(username: username, password: password, options: options)
.resultPublisher
.sink {
if case let .failure(authError) = $0 {
print("An error occurred while registering a user \(authError)")
}
}
receiveValue: { signUpResult in
if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
print("Delivery details \(String(describing: deliveryDetails))")
} else {
print("SignUp Complete")
}
}
return sink
}

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.

func confirmSignIn() {
Amplify.Auth.confirmSignIn(challengeResponse: "<confirmation code received via SMS>") { result in
switch result {
case .success(let signInResult):
print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
case .failure(let error):
print("Confirm sign in failed \(error)")
}
}
}
func confirmSignIn() -> AnyCancellable {
Amplify.Auth.confirmSignIn(challengeResponse: "<confirmation code received via SMS>")
.resultPublisher
.sink {
if case let .failure(authError) = $0 {
print("Confirm sign in failed \(authError)")
}
}
receiveValue: { signInResult in
print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
}
}