Page updated Jan 16, 2024

Switching authentication flows

For client side authentication there are three different flows:

  1. USER_SRP_AUTH: The USER_SRP_AUTH flow uses the SRP protocol (Secure Remote Password) where the password never leaves the client and is unknown to the server. This is the recommended flow and is used by default.

  2. USER_PASSWORD_AUTH: The USER_PASSWORD_AUTH flow will send user credentials unencrypted to the backend. If you want to migrate users to Cognito using the "Migration" trigger and avoid forcing users to reset their passwords, you will need to use this authentication type because the Lambda function invoked by the trigger needs to verify the supplied credentials.

  3. CUSTOM_AUTH: The CUSTOM_AUTH flow is used to allow for a series of challenge and response cycles that can be customized to meet different requirements.

To configure Auth to use the different flows:

1Auth.configure({
2 // other configurations...
3 // ...
4 authenticationFlowType: 'USER_SRP_AUTH' | 'USER_PASSWORD_AUTH' | 'CUSTOM_AUTH'
5});

For more information about authentication flows, please visit AWS Cognito developer documentation

USER_PASSWORD_AUTH flow

A use case for the USER_PASSWORD_AUTH authentication flow is migrating users into Amazon Cognito

Set up auth backend

In order to use the authentication flow USER_PASSWORD_AUTH, your Cognito app client has to be configured to allow it. In the AWS Console, this is done by ticking the checkbox at General settings > App clients > Show Details (for the affected client) > Enable username-password (non-SRP) flow. If you're using the AWS CLI or CloudFormation, update your app client by adding USER_PASSWORD_AUTH to the list of "Explicit Auth Flows".

Migrate users with Amazon Cognito

Amazon Cognito provides a trigger to migrate users from your existing user directory seamlessly into Cognito. You achieve this by configuring your User Pool's "Migration" trigger which invokes a Lambda function whenever a user that does not already exist in the user pool authenticates, or resets their password.

In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's a documentation here on how to set up this migration flow and more detailed instructions here on how the lambda should handle request and response objects.

CUSTOM_AUTH flow

Amazon Cognito User Pools supports customizing the authentication flow to enable custom challenge types, in addition to a password in order to verify the identity of users. These challenge types may include CAPTCHAs or dynamic challenge questions.

To define your challenges for custom authentication flow, you need to implement three Lambda triggers for Amazon Cognito.

For more information about working with Lambda Triggers for custom authentication challenges, please visit Amazon Cognito Developer Documentation.

Custom authentication flow

To initiate a custom authentication flow in your app, call signIn without a password. A custom challenge needs to be answered using the sendCustomChallengeAnswer method:

1import { Auth } from 'aws-amplify';
2
3Auth.configure({
4 // other configurations
5 // ...
6 authenticationFlowType: 'CUSTOM_AUTH'
7});
8
9type SignInParameters = {
10 username: string;
11 password: string;
12};
13
14export async function signIn({ username, password }: SignInParameters) {
15 const challengeResponse = 'the answer for the challenge';
16 try {
17 const user = await Auth.signIn(username, password);
18 if (user?.challengeName === 'CUSTOM_CHALLENGE') {
19 try {
20 // to send the answer of the custom challenge
21 const challengeAnswerResponse = await Auth.sendCustomChallengeAnswer(
22 user,
23 challengeResponse
24 );
25 console.log(challengeAnswerResponse);
26 } catch (err) {
27 console.log(err);
28 }
29 }
30 } catch (err) {
31 console.log(err);
32 }
33}
1import { Auth } from 'aws-amplify';
2
3Auth.configure({
4 // other configurations
5 // ...
6 authenticationFlowType: 'CUSTOM_AUTH'
7});
8
9async function signIn(username, password) {
10 const challengeResponse = 'the answer for the challenge';
11 try {
12 const user = await Auth.signIn(username, password);
13 if (user?.challengeName === 'CUSTOM_CHALLENGE') {
14 try {
15 // to send the answer of the custom challenge
16 const challengeAnswerResponse = await Auth.sendCustomChallengeAnswer(
17 user,
18 challengeResponse
19 );
20 console.log(challengeAnswerResponse);
21 } catch (err) {
22 console.log(err);
23 }
24 }
25 } catch (err) {
26 console.log(err);
27 }
28}

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:

1import { Handler } from 'aws-lambda';
2
3export const handler: Handler = async (event) => {
4 if (!event?.request?.session || event?.request?.session?.length === 0) {
5 event.response.publicChallengeParameters = {
6 captchaUrl: 'url/123.jpg'
7 };
8 event.response.privateChallengeParameters = {
9 answer: '5'
10 };
11 event.response.challengeMetadata = 'CAPTCHA_CHALLENGE';
12 }
13 return event;
14};
1export const handler = async (event) => {
2 if (
3 !Array.isArray(event?.request?.session) ||
4 event?.request?.session?.length
5 ) {
6 event.response.publicChallengeParameters = {
7 captchaUrl: 'url/123.jpg'
8 };
9 event.response.privateChallengeParameters = {
10 answer: '5'
11 };
12 event.response.challengeMetadata = 'CAPTCHA_CHALLENGE';
13 }
14 return event;
15};

This Define Auth Challenge Lambda Trigger defines a custom challenge:

1import { Handler } from 'aws-lambda';
2
3export const handler: Handler = async (event) => {
4 if (
5 !Array.isArray(event?.request?.session) ||
6 event?.request?.session?.length
7 ) {
8 // If you don't have a session or it is empty then send a CUSTOM_CHALLENGE
9 event.response.challengeName = 'CUSTOM_CHALLENGE';
10 event.response.failAuthentication = false;
11 event.response.issueTokens = false;
12 } else if (
13 event?.request?.session?.length === 1 &&
14 event?.request?.session[0]?.challengeResult
15 ) {
16 // If you passed the CUSTOM_CHALLENGE then issue token
17 event.response.failAuthentication = false;
18 event.response.issueTokens = true;
19 } else {
20 // Something is wrong. Fail authentication
21 event.response.failAuthentication = true;
22 event.response.issueTokens = false;
23 }
24
25 return event;
26};
1export const handler = async (event) => {
2 if (
3 !Array.isArray(event?.request?.session) ||
4 event?.request?.session?.length
5 ) {
6 // If you don't have a session or it is empty then send a CUSTOM_CHALLENGE
7 event.response.challengeName = 'CUSTOM_CHALLENGE';
8 event.response.failAuthentication = false;
9 event.response.issueTokens = false;
10 } else if (
11 event?.request?.session?.length === 1 &&
12 event?.request?.session[0]?.challengeResult
13 ) {
14 // If you passed the CUSTOM_CHALLENGE then issue token
15 event.response.failAuthentication = false;
16 event.response.issueTokens = true;
17 } else {
18 // Something is wrong. Fail authentication
19 event.response.failAuthentication = true;
20 event.response.issueTokens = false;
21 }
22
23 return event;
24};

The Verify Auth Challenge Response Lambda Trigger is used to verify a challenge answer:

1import { Handler } from 'aws-lambda';
2
3export const handler: Handler = async (event, context) => {
4 if (
5 event?.request?.privateChallengeParameters?.answer ===
6 event?.request?.challengeAnswer
7 ) {
8 event.response.answerCorrect = true;
9 } else {
10 event.response.answerCorrect = false;
11 }
12 return event;
13};
1export const handler = async (event, context) => {
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 return event;
11};