Page updated Nov 14, 2023

Sign-in with custom flow

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

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 configured to perform a custom authentication flow defined by you. The following guide shows how to setup a simple passwordless authentication flow.

Prerequisites

  • An iOS application targeting at least iOS 11.0 with Amplify libraries integrated

Configure Auth Category

In terminal, navigate to your project, run amplify add auth, and choose the following options:

1? Do you want to use the default authentication and security configuration? Manual configuration?
2 `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)`
3? Please provide a friendly name for your resource that will be used to label this category in the project:
4 `<hit enter to take default or enter a custom label>`
5? Please enter a name for your identity pool.
6 `<hit enter to take default or enter a custom name>`
7? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM)
8 `No`
9? Do you want to enable 3rd party authentication providers in your identity pool?
10 `No`
11? Please provide a name for your user pool:
12 `<hit enter to take default or enter a custom name>`
13? How do you want users to be able to sign in?
14 `Username`
15? Do you want to add User Pool Groups?
16 `No`
17? Do you want to add an admin queries API?
18 `No`
19? Multifactor authentication (MFA) user login options:
20 `OFF`
21? Email based user registration/forgot password:
22 `Enabled (Requires per-user email entry at registration)`
23? Please specify an email verification subject:
24 `Your verification code`
25? Please specify an email verification message:
26 `Your verification code is {####}`
27? Do you want to override the default password policy for this User Pool?
28 `No`
29? What attributes are required for signing up?
30 `Email`
31? Specify the app's refresh token expiration period (in days):
32 `30`
33? Do you want to specify the user attributes this app can read and write?
34 `No`
35? Do you want to enable any of the following capabilities?
36 `NA`
37? Do you want to use an OAuth flow?
38 `No`
39? Do you want to configure Lambda Triggers for Cognito?
40 `Yes`
41? Which triggers do you want to enable for Cognito?
42 `Create Auth Challenge, Define Auth Challenge, Verify Auth Challenge Response`
43? What functionality do you want to use for Create Auth Challenge?
44 `Custom Auth Challenge Scaffolding (Creation)`
45? What functionality do you want to use for Define Auth Challenge?
46 `Custom Auth Challenge Scaffolding (Definition)`
47? What functionality do you want to use for Verify Auth Challenge Response?
48 `Custom Auth Challenge Scaffolding (Verification)`
49
50? Do you want to edit your boilerplate-create-challenge function now?
51 `Yes`
52? Please edit the file in your editor: <local file path>/src/boilerplate-create-challenge.js

The boilerplate for Create Auth Challenge opens in your favorite code editor. Enter the following code to this file:

1//crypto-secure-random-digit is used here to get random challenge code - https://github.com/ottokruse/crypto-secure-random-digit
2const digitGenerator = require('crypto-secure-random-digit');
3
4function sendChallengeCode(emailAddress, secretCode) {
5 // Use SES or custom logic to send the secret code to the user.
6}
7
8function createAuthChallenge(event) {
9 if (event.request.challengeName === 'CUSTOM_CHALLENGE') {
10 // Generate a random code for the custom challenge
11 const challengeCode = digitGenerator.randomDigits(6).join('');
12
13 // Send the custom challenge to the user
14 sendChallengeCode(event.request.userAttributes.email, challengeCode);
15
16 event.response.privateChallengeParameters = {};
17 event.response.privateChallengeParameters.answer = challengeCode;
18 }
19}
20
21exports.handler = async (event) => {
22 createAuthChallenge(event);
23};

Note that the sendChallengeCode method is empty, you can use AWS service like SES to setup email delivery and populate the function sendChallengeCode to send the challenge code to the user.

Amazon Cognito invokes the Create Auth Challenge trigger after Define Auth Challenge to create a custom challenge. In this lambda trigger you define the challenge to present to the user. privateChallengeParameters contains all the information to validate the response from the user. Save and close the file. Now open the file under "<your_xcode_project>/amplify/backend/function/<project_code>CreateAuthChallenge/src/package.json" and add the following:

1"dependencies": {
2 "crypto-secure-random-digit": "^1.0.9"
3}

Save and close the file, then switch back to the terminal and follow the instructions:

1? Press enter to continue
2 `Hit Enter`
3
4? Do you want to edit your boilerplate-define-challenge function now?
5 `Yes`
6? Please edit the file in your editor: <local file path>/src/boilerplate-define-challenge.js

The boilerplate for Define Auth Challenge opens in your favorite code editor. Enter the following code to this file:

1exports.handler = async function (event) {
2 if (
3 event.request.session.length == 1 &&
4 event.request.session[0].challengeName == 'SRP_A'
5 ) {
6 event.response.issueTokens = false;
7 event.response.failAuthentication = false;
8 event.response.challengeName = 'CUSTOM_CHALLENGE';
9 } else if (
10 event.request.session.length == 2 &&
11 event.request.session[1].challengeName == 'CUSTOM_CHALLENGE' &&
12 event.request.session[1].challengeResult == true
13 ) {
14 event.response.issueTokens = true;
15 event.response.failAuthentication = false;
16 event.response.challengeName = 'CUSTOM_CHALLENGE';
17 } else {
18 event.response.issueTokens = false;
19 event.response.failAuthentication = true;
20 }
21};

Amazon Cognito invokes the Define Auth Challenge trigger to initiate the custom authentication flow.

The Amplify Auth library always starts with an SRP_A flow, so in the code above, you bypass SRP_A and return CUSTOM_CHALLENGE in the first step. In the second step, if CUSTOM_CHALLENGE returns with challengeResult == true you recognize the custom auth challenge is successful, and tell Cognito to issue tokens. In the last else block you tell Cognito to fail the authentication flow.

Save and close the file, then switch back to the terminal and follow the instructions:

1? Press enter to continue
2 `Hit Enter`
3
4? Do you want to edit your boilerplate-verify function now?
5 `Yes`
6? Please edit the file in your editor: <local file path>/src/boilerplate-verify.js

The boilerplate for Verify Auth Challenge opens in your favorite code editor. Enter the following code to this file:

1function verifyAuthChallengeResponse(event) {
2 if (
3 event.request.privateChallengeParameters.answer ===
4 event.request.challengeAnswer
5 ) {
6 event.response.answerCorrect = true;
7 } else {
8 event.response.answerCorrect = false;
9 }
10}
11
12exports.handler = async (event) => {
13 verifyAuthChallengeResponse(event);
14};

Amazon Cognito invokes the Verify Auth Challenge trigger to verify if the response from the end user for a custom challenge is valid or not. The response from the user will be available in event.request.challengeAnswer. The code above compares that with privateChallengeParameters value set in the Create Auth Challenge trigger. Save and close the file, then switch back to the terminal and follow the instructions:

1? Press enter to continue
2 `Hit Enter`

Once finished, run amplify push to publish your changes.

Register a user

The CLI flow as mentioned above requires a username 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, email: String) {
2 let userAttributes = [AuthUserAttribute(.email, value: email)]
3 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
4 Amplify.Auth.signUp(username: username, password: UUID().uuidString, options: options) { result in
5 switch result {
6 case .success(let signUpResult):
7 if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
8 print("Delivery details \(String(describing: deliveryDetails))")
9 } else {
10 print("Signup Complete")
11 }
12 case .failure(let error):
13 print("An error occurred while registering a user \(error)")
14 }
15 }
16}
1func signUp(username: String, password: String, email: String) -> AnyCancellable {
2 let userAttributes = [AuthUserAttribute(.email, value: email)]
3 let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
4 let sink = Amplify.Auth.signUp(username: username, password: password, options: options)
5 .resultPublisher
6 .sink {
7 if case let .failure(authError) = $0 {
8 print("An error occurred while registering a user \(authError)")
9 }
10 }
11 receiveValue: { signUpResult in
12 if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep {
13 print("Delivery details \(String(describing: deliveryDetails))")
14 } else {
15 print("Signup Complete")
16 }
17
18 }
19 return sink
20}

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) {
2 Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode) { result in
3 switch result {
4 case .success:
5 print("Confirm signUp succeeded")
6 case .failure(let error):
7 print("An error occurred while confirming sign up \(error)")
8 }
9 }
10}
1func confirmSignUp(for username: String, with confirmationCode: String) -> AnyCancellable {
2 Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode)
3 .resultPublisher
4 .sink {
5 if case let .failure(authError) = $0 {
6 print("An error occurred while confirming sign up \(authError)")
7 }
8 }
9 receiveValue: { _ in
10 print("Confirm signUp succeeded")
11 }
12}

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 from the user. After the user enters the username you can start the sign in flow by calling the following method:

1func signIn(username: String) {
2 Amplify.Auth.signIn(username: username) { result in
3 switch result {
4 case .success:
5 if case .confirmSignInWithCustomChallenge(_) = result.nextStep {
6 // Ask the user to enter the custom challenge.
7 } else {
8 print("Sign in succeeded")
9 }
10 case .failure(let error):
11 print("Sign in failed \(error)")
12 }
13 }
14}
1func signIn(username: String, password: String) -> AnyCancellable {
2 Amplify.Auth.signIn(username: username, password: password)
3 .resultPublisher
4 .sink {
5 if case let .failure(authError) = $0 {
6 print("Sign in failed \(authError)")
7 }
8 }
9 receiveValue: { result in
10 if case .confirmSignInWithCustomChallenge(_) = result.nextStep {
11 // Ask the user to enter the custom challenge.
12 } else {
13 print("Sign in succeeded")
14 }
15 }
16}

Since this is a custom authentication flow with a challenge, the result of the signin process has a next step .confirmSignInWithCustomChallenge. Implement a UI to allow the user to enter the custom challenge.

Confirm sign in with custom challenge

Get the custom challenge (1234 in this case) from the user and pass it to the confirmSignin() api.

1func customChallenge(response: String) {
2 Amplify.Auth.confirmSignIn(challengeResponse: response) { result in
3 switch result {
4 case .success:
5 print("Confirm sign in succeeded")
6 case .failure(let error):
7 print("Confirm sign in failed \(error)")
8 }
9 }
10}
1func customChallenge(response: String) -> AnyCancellable {
2 Amplify.Auth.confirmSignIn(challengeResponse: response)
3 .resultPublisher
4 .sink {
5 if case let .failure(authError) = $0 {
6 print("Confirm sign in failed \(authError)")
7 }
8 }
9 receiveValue: { _ in
10 print("Confirm sign in succeeded")
11 }
12}

Lambda Trigger Setup

The Amplify CLI can be used to generate triggers required by a custom authentication flow. See the CLI Documentation for details. The CLI will create a custom auth flow skeleton that you can manually edit.

More information on available triggers can be found in the Cognito documentation.

AWSCognitoAuthPlugin assumes the custom auth flow starts with username and password (SRP_A). If you want a passwordless authentication flow, modify your Define Auth Challenge Lambda trigger to bypass the initial username/password verification and proceed to the custom challenge:

1exports.handler = (event, context) => {
2 if (event.request.session.length === 1 &&
3 event.request.session[0].challengeName === 'SRP_A') {
4 event.response.issueTokens = false;
5 event.response.failAuthentication = false;
6 event.response.challengeName = 'CUSTOM_CHALLENGE';
7 } else if (
8 event.request.session.length === 2 &&
9 event.request.session[1].challengeName === 'CUSTOM_CHALLENGE' &&
10 event.request.session[1].challengeResult === true
11 ) {
12 event.response.issueTokens = true;
13 event.response.failAuthentication = false;
14 } else {
15 event.response.issueTokens = false;
16 event.response.failAuthentication = true;
17 }
18 context.done(null, event);
19};

You also need to pass a dummy password during the signup process as shown above.

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

1Sign in succeeded