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 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 or later. (Preview support - see below for more details.)
For a full example, 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:
{ "name": "<AUTH_CHALLENGE_NAME>", "version": "2.0.0", "description": "Lambda function generated by Amplify", "main": "index.js", "license": "Apache-2.0", "devDependencies": { "@types/aws-lambda": "^8.10.92" }, // <- Include comma
// Add the following lines "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 == 0) { event.response.issueTokens = false; event.response.failAuthentication = false; event.response.challengeName = 'CUSTOM_CHALLENGE'; } else if ( event.request.session.length == 1 && event.request.session[0].challengeName == 'CUSTOM_CHALLENGE' && event.request.session[0].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. In the first step you define the auth flow to go through Custom Challenge. In the second if block, 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) async { let userAttributes = [AuthUserAttribute(.email, value: email)] let options = AuthSignUpRequest.Options(userAttributes: userAttributes) do { let signUpResult = try await Amplify.Auth.signUp( username: username, password: UUID().uuidString, options: options )
if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep { print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))") } else { print("Signup Complete") } } catch let error as AuthError { print("An error occurred while registering a user \(error)") } catch { print("Unexpected error: \(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.Publisher.create { try await Amplify.Auth.signUp( username: username, password: UUID().uuidString, options: options ) }.sink { if case let .failure(authError) = $0 { print("An error occurred while registering a user \(authError)") } } receiveValue: { signUpResult in if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep { print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))") } 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) 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") }}
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) async { do { let options = AWSAuthSignInOptions(authFlowType: .customWithoutSRP) let signInResult = try await Amplify.Auth.signIn(username: username, options: .init(pluginOptions: options)) if case .confirmSignInWithCustomChallenge(_) = signInResult.nextStep { // Ask the user to enter the custom challenge. } else { print("Sign in succeeded") } } catch let error as AuthError { print("Sign in failed \(error)") } catch { print("Unexpected error: \(error)") }}
func signIn(username: String) -> AnyCancellable { Amplify.Publisher.create { let options = AWSAuthSignInOptions(authFlowType: .customWithoutSRP) try await Amplify.Auth.signIn(username: username, options: .init(pluginOptions: options)) }.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) async { do { _ = try await Amplify.Auth.confirmSignIn(challengeResponse: response) print("Confirm sign in succeeded") } catch let error as AuthError { print("Confirm sign in failed \(error)") } catch { print("Unexpected error: \(error)") }}
func customChallenge(response: String) -> AnyCancellable { Amplify.Publisher.create { try await Amplify.Auth.confirmSignIn(challengeResponse: response) }.sink { if case let .failure(authError) = $0 { print("Confirm sign in failed \(authError)") } } receiveValue: { _ in print("Confirm sign in succeeded") }}
You will know the sign in flow is complete if you see the following in your console window:
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.
Custom Auth Flow with SRP
Cognito User Pool allows to start the custom authentication flow with SRP as the first step. If you would like to use this flow, setup Define Auth Lambda trigger to handle SRP_A as the first challenge as shown below:
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 = 'PASSWORD_VERIFIER'; } else if (event.request.session.length == 2 && event.request.session[1].challengeName == 'PASSWORD_VERIFIER' && event.request.session[1].challengeResult == true) { event.response.issueTokens = false; event.response.failAuthentication = false; event.response.challengeName = 'CUSTOM_CHALLENGE'; } else if (event.request.session.length == 3 && event.request.session[2].challengeName == 'CUSTOM_CHALLENGE' && event.request.session[2].challengeResult == true) { event.response.issueTokens = true; event.response.failAuthentication = false; } else { event.response.issueTokens = false; event.response.failAuthentication = true; } context.done(null, event);};
If your lambda is setup to start with SRP
as the first step, make sure to initiate the signIn process with customWithSRP
as the authentication flow:
let options = AWSAuthSignInOptions( authFlowType: .customWithSRP)let signInResult = try await Amplify.Auth.signIn( username: username, password: password, options: .init(pluginOptions: options))
CAPTCHA-based authentication
Here is the sample for creating a CAPTCHA challenge with a Lambda Trigger.
The Create Auth Challenge Lambda Trigger
creates a CAPTCHA as a challenge to the user. The URL for the CAPTCHA image and the expected answer is added to the private challenge parameters:
export const handler = async (event) => { if (!event.request.session || event.request.session.length === 0) { event.response.publicChallengeParameters = { captchaUrl: <captcha url>, }; event.response.privateChallengeParameters = { answer: <expected answer>, }; event.response.challengeMetadata = "CAPTCHA_CHALLENGE"; } return event;};
This Define Auth Challenge Lambda Trigger
defines a custom challenge:
export const handler = async (event) => { if (!event.request.session || event.request.session.length === 0) { // If we don't have a session or it is empty then send a CUSTOM_CHALLENGE event.response.challengeName = "CUSTOM_CHALLENGE"; event.response.failAuthentication = false; event.response.issueTokens = false; } else if (event.request.session.length === 1 && event.request.session[0].challengeResult === true) { // If we passed the CUSTOM_CHALLENGE then issue token event.response.failAuthentication = false; event.response.issueTokens = true; } else { // Something is wrong. Fail authentication event.response.failAuthentication = true; event.response.issueTokens = false; }
return event;};
The Verify Auth Challenge Response Lambda Trigger
is used to verify a challenge answer:
export const handler = async (event, context) => { if (event.request.privateChallengeParameters.answer === event.request.challengeAnswer) { event.response.answerCorrect = true; } else { event.response.answerCorrect = false; }
return event;};