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 to the backend without applying SRP encryption. 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_WITH_SRP & CUSTOM_WITHOUT_SRP: Allows for a series of challenge and response cycles that can be customized to meet different requirements.

The Auth flow can be customized when calling signIn, for example:

1signIn({
2 username,
3 password,
4 options: {
5 authFlowType: 'USER_PASSWORD_AUTH'
6 }
7})

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_WITH_SRP & CUSTOM_WITHOUT_SRP flows

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. The CUSTOM_WITH_SRP flow requires a password when calling signIn. Both of these flows map to the CUSTOM_AUTH flow in Cognito.

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 confirmSignIn API:

1import { signIn, confirmSignIn } from 'aws-amplify/auth';
2
3export async function handleSignIn(username: string) {
4 const challengeResponse = 'the answer for the challenge';
5 try {
6 const { nextStep } = await signIn({
7 username,
8 options: {
9 authFlowType: 'CUSTOM_WITHOUT_SRP',
10 },
11 });
12 if (nextStep.signInStep === 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE') {
13 try {
14 // to send the answer of the custom challenge
15 const output = await confirmSignIn({ challengeResponse });
16 console.log(output);
17 } catch (err) {
18 console.log(err);
19 }
20 }
21 } catch (err) {
22 console.log(err);
23 }
24}
1import { signIn, confirmSignIn } from 'aws-amplify/auth';
2
3export async function handleSignIn(username) {
4 const challengeResponse = 'the answer for the challenge';
5 try {
6 const { nextStep } = await signIn({
7 username,
8 options: {
9 authFlowType: 'CUSTOM_WITHOUT_SRP',
10 },
11 });
12 if (nextStep.signInStep === 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE') {
13 try {
14 // to send the answer of the custom challenge
15 const output = await confirmSignIn({ challengeResponse });
16 console.log(output);
17 } catch (err) {
18 console.log(err);
19 }
20 }
21 } catch (err) {
22 console.log(err);
23 }
24}

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 (!Array.isArray(event?.request?.session) || event?.request?.session?.length) {
3 event.response.publicChallengeParameters = {
4 captchaUrl: 'url/123.jpg',
5 };
6 event.response.privateChallengeParameters = {
7 answer: '5',
8 };
9 event.response.challengeMetadata = 'CAPTCHA_CHALLENGE';
10 }
11 return event;
12};

This Define Auth Challenge Lambda Trigger defines a custom challenge:

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

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