Sign-in with custom flow
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
- For a full example of please follow the project setup walkthrough
Configure Auth Category
In terminal, navigate to your project, run amplify add auth
, and choose 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: `<hit enter to take default or enter a custom label>`? Please enter a name for your identity pool. `<hit enter to take default or enter a custom name>`? Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) `No`? Do you want to enable 3rd party authentication providers in your identity pool? `No`? Please provide a name for your user pool: `<hit enter to take default or enter a custom name>`? 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: `OFF`? 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`? What attributes are required for signing up? `Email`? 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? `Yes`? Which triggers do you want to enable for Cognito? `Create Auth Challenge, Define Auth Challenge, Verify Auth Challenge Response`? What functionality do you want to use for Create Auth Challenge? `Custom Auth Challenge Scaffolding (Creation)`? What functionality do you want to use for Define Auth Challenge? `Custom Auth Challenge Scaffolding (Definition)`? What functionality do you want to use for Verify Auth Challenge Response? `Custom Auth Challenge Scaffolding (Verification)`
? Do you want to edit your boilerplate-create-challenge function now? `Yes`? 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:
//crypto-secure-random-digit is used here to get random challenge code - https://github.com/ottokruse/crypto-secure-random-digitconst digitGenerator = require('crypto-secure-random-digit');
function sendChallengeCode(emailAddress, secretCode) { // Use SES or custom logic to send the secret code to the user.}
function createAuthChallenge(event) { if (event.request.challengeName === 'CUSTOM_CHALLENGE') { // Generate a random code for the custom challenge const challengeCode = digitGenerator.randomDigits(6).join('');
// Send the custom challenge to the user sendChallengeCode(event.request.userAttributes.email, challengeCode);
event.response.privateChallengeParameters = {}; event.response.privateChallengeParameters.answer = challengeCode; }}
exports.handler = async (event) => { createAuthChallenge(event);};
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:
"dependencies": { "crypto-secure-random-digit": "^1.0.9"}
Save and close the file, then switch back to the terminal and follow the instructions:
? Press enter to continue `Hit Enter`
? Do you want to edit your boilerplate-define-challenge function now? `Yes`? 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:
exports.handler = async function (event) { if ( event.request.session.length == 1 && event.request.session[0].challengeName == 'SRP_A' ) { event.response.issueTokens = false; event.response.failAuthentication = false; event.response.challengeName = 'CUSTOM_CHALLENGE'; } else if ( event.request.session.length == 2 && event.request.session[1].challengeName == 'CUSTOM_CHALLENGE' && event.request.session[1].challengeResult == true ) { event.response.issueTokens = true; event.response.failAuthentication = false; event.response.challengeName = 'CUSTOM_CHALLENGE'; } else { event.response.issueTokens = false; event.response.failAuthentication = true; }};
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:
? Press enter to continue `Hit Enter`
? Do you want to edit your boilerplate-verify function now? `Yes`? 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:
function verifyAuthChallengeResponse(event) { if ( event.request.privateChallengeParameters.answer === event.request.challengeAnswer ) { event.response.answerCorrect = true; } else { event.response.answerCorrect = false; }}
exports.handler = async (event) => { verifyAuthChallengeResponse(event);};
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:
? Press enter to continue `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.
func signUp(username: String, email: String) { let userAttributes = [AuthUserAttribute(.email, value: email)] let options = AuthSignUpRequest.Options(userAttributes: userAttributes) Amplify.Auth.signUp(username: username, password: UUID().uuidString, 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 from the user. After the user enters the username you can start the sign in flow by calling the following method:
func signIn(username: String) { Amplify.Auth.signIn(username: username) { result in switch result { case .success: if case .confirmSignInWithCustomChallenge(_) = result.nextStep { // Ask the user to enter the custom challenge. } else { 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: { result in if case .confirmSignInWithCustomChallenge(_) = result.nextStep { // Ask the user to enter the custom challenge. } else { print("Sign in succeeded") } }}
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.
func customChallenge(response: String) { Amplify.Auth.confirmSignIn(challengeResponse: response) { result in switch result { case .success: print("Confirm sign in succeeded") case .failure(let error): print("Confirm sign in failed \(error)") } }}
func customChallenge(response: String) -> AnyCancellable { Amplify.Auth.confirmSignIn(challengeResponse: response) .resultPublisher .sink { if case let .failure(authError) = $0 { print("Confirm sign in failed \(authError)") } } receiveValue: { _ in print("Confirm sign in succeeded") }}
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:
exports.handler = (event, context) => { if (event.request.session.length === 1 && event.request.session[0].challengeName === 'SRP_A') { event.response.issueTokens = false; event.response.failAuthentication = false; event.response.challengeName = 'CUSTOM_CHALLENGE'; } else if ( event.request.session.length === 2 && event.request.session[1].challengeName === 'CUSTOM_CHALLENGE' && event.request.session[1].challengeResult === true ) { event.response.issueTokens = true; event.response.failAuthentication = false; } else { event.response.issueTokens = false; event.response.failAuthentication = true; } context.done(null, event);};
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:
Sign in succeeded