Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Feb 21, 2024

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 Android application targeting at least Android SDK API level 24 with Amplify libraries integrated

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 in this file:

//crypto-secure-random-digit is used here to get random challenge code - https://github.com/ottokruse/crypto-secure-random-digit
const 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);
};

Note that the sendChallengeCode method is empty. You can use an 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_android_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 in 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 the 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.

AuthSignUpOptions options = AuthSignUpOptions.builder()
.userAttribute(AuthUserAttributeKey.email(), "my@email.com")
.build();
Amplify.Auth.signUp("username", "Password123", options,
result -> Log.i("AuthQuickStart", "Result: " + result.toString()),
error -> Log.e("AuthQuickStart", "Sign up failed", error)
);
val options = AuthSignUpOptions.builder()
.userAttribute(AuthUserAttributeKey.email(), "my@email.com")
.build()
Amplify.Auth.signUp("username", "Password123", options,
{ Log.i("AuthQuickStart", "Sign up succeeded: $it") },
{ Log.e ("AuthQuickStart", "Sign up failed", it) }
)
val options = AuthSignUpOptions.builder()
.userAttribute(AuthUserAttributeKey.email(), "my@email.com")
.build()
try {
val result = Amplify.Auth.signUp("username", "Password123", options)
Log.i("AuthQuickStart", "Result: $result")
} catch (error: AuthException) {
Log.e("AuthQuickStart", "Sign up failed", error)
}
RxAmplify.Auth.signUp(
"username",
"Password123",
AuthSignUpOptions.builder().userAttribute(AuthUserAttributeKey.email(), "my@email.com").build())
.subscribe(
result -> Log.i("AuthQuickStart", "Result: " + result.toString()),
error -> Log.e("AuthQuickStart", "Sign up failed", error)
);

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.

Amplify.Auth.confirmSignUp(
"username",
"the code you received via email",
result -> Log.i("AuthQuickstart", result.isSignUpComplete() ? "Confirm signUp succeeded" : "Confirm sign up not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);
Amplify.Auth.confirmSignUp(
"username", "the code you received via email",
{ result ->
if (result.isSignUpComplete) {
Log.i("AuthQuickstart", "Confirm signUp succeeded")
} else {
Log.i("AuthQuickstart","Confirm sign up not complete")
}
},
{ Log.e("AuthQuickstart", "Failed to confirm sign up", it) }
)
try {
val code = "code you received via email"
val result = Amplify.Auth.confirmSignUp("username", code)
if (result.isSignUpComplete) {
Log.i("AuthQuickstart", "Signup confirmed")
} else {
Log.i("AuthQuickstart", "Signup confirmation not yet complete")
}
} catch (error: AuthException) {
Log.e("AuthQuickstart", "Failed to confirm signup", error)
}
RxAmplify.Auth.confirmSignUp("username", "the code you received via email")
.subscribe(
result -> Log.i("AuthQuickstart", result.isSignUpComplete() ? "Confirm signUp succeeded" : "Confirm sign up not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);

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

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:

AWSCognitoAuthSignInOptions options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITHOUT_SRP)
.build();
Amplify.Auth.signIn(
"username",
"password",
options,
result -> Log.i("AuthQuickstart", result.isSignedIn() ? "Sign in succeeded" : "Sign in not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);
val options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITHOUT_SRP)
.build()
Amplify.Auth.signIn(
"username",
"password",
options,
{ result ->
if (result.isSignedIn) {
Log.i("AuthQuickstart", "Sign in succeeded")
} else {
Log.i("AuthQuickstart", "Sign in not complete")
}
},
{ Log.e("AuthQuickstart", "Failed to sign in", it) }
)
val options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITHOUT_SRP)
.build()
try {
val result = Amplify.Auth.signIn("username", "password", options)
if (result.isSignedIn) {
Log.i("AuthQuickstart", "Sign in succeeded")
} else {
Log.e("AuthQuickstart", "Sign in not complete")
}
} catch (error: AuthException) {
Log.e("AuthQuickstart", "Sign in failed", error)
}
AWSCognitoAuthSignInOptions options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITHOUT_SRP)
.build();
RxAmplify.Auth.signIn("username", "password", options)
.subscribe(
result -> Log.i("AuthQuickstart", result.isSignedIn() ? "Sign in succeeded" : "Sign in not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);

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.

Amplify.Auth.confirmSignIn(
"confirmation",
result -> Log.i("AuthQuickstart", "Confirm sign in succeeded: " + result.toString()),
error -> Log.e("AuthQuickstart", "Failed to confirm sign in", error)
);
Amplify.Auth.confirmSignIn("confirmation",
{ Log.i("AuthQuickstart", "Confirm sign in succeeded: $it") },
{ Log.e("AuthQuickstart", "Failed to confirm sign in", it) }
)
try {
val result = Amplify.Auth.confirmSignIn("confirmation")
Log.i("AuthQuickstart", "Confirm sign in succeeded: $result")
} catch (error: AuthException) {
Log.e("AuthQuickstart", "Failed to confirm signin", error)
}
RxAmplify.Auth.confirmSignIn("confirmation")
.subscribe(
result -> Log.i("AuthQuickstart", result.toString()),
error -> Log.e("AuthQuickstart", error.toString())
);

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:

AWSCognitoAuthSignInOptions options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITH_SRP)
.build();
Amplify.Auth.signIn(
"username",
"password",
options,
result -> Log.i("AuthQuickstart", result.isSignedIn() ? "Sign in succeeded" : "Sign in not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);
val options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITH_SRP)
.build()
Amplify.Auth.signIn(
"username",
"password",
options,
{ result ->
if (result.isSignedIn) {
Log.i("AuthQuickstart", "Sign in succeeded")
} else {
Log.i("AuthQuickstart", "Sign in not complete")
}
},
{ Log.e("AuthQuickstart", "Failed to sign in", it) }
)
val options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITH_SRP)
.build()
try {
val result = Amplify.Auth.signIn("username", "password", options)
if (result.isSignedIn) {
Log.i("AuthQuickstart", "Sign in succeeded")
} else {
Log.e("AuthQuickstart", "Sign in not complete")
}
} catch (error: AuthException) {
Log.e("AuthQuickstart", "Sign in failed", error)
}
AWSCognitoAuthSignInOptions options = AWSCognitoAuthSignInOptions.builder()
.authFlowType(AuthFlowType.CUSTOM_AUTH_WITH_SRP)
.build();
RxAmplify.Auth.signIn("username", "password", options)
.subscribe(
result -> Log.i("AuthQuickstart", result.isSignedIn() ? "Sign in succeeded" : "Sign in not complete"),
error -> Log.e("AuthQuickstart", error.toString())
);

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 are 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;
};