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
Amplify Flutter requires a minimum target platform for iOS (13.0), Android (API level 24), and macOS (10.15). Additional setup is required for some target platforms. Please see the platform setup guide for more details on platform specific setup.
Configure Auth Category
How Custom Auth Works
The custom authentication flow supported by Amazon Cognito uses a series of AWS Lambda triggers, which are serverless functions invoked when particular events occur in Cognito. Together, these triggers allow you to establish a series of 'challenges' to which your users must successfully respond in order to authenticate.
The custom authentication flow consists of the following triggers, invoked in order:
-
Define Auth Challenge: This trigger defines the sequential series of challenges that the user will need to complete in the flow. These challenges can be custom challenges, as well as traditional SRP_A ] (with username/password verification).
-
Create Auth Challenge: This trigger defines the expected response for custom challenges, as well as key/value pairs that can be sent back to the client application to help guide your end users.
-
Verify Auth Challenge: This trigger is used to verify if the provided response for a given challenge is correct.
Setting-up custom auth flow with the Amplify CLI
The Amplify CLI can help you setup the AWS Lambda triggers for your custom authentication flow. In the 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; event.response.publicChallengeParameters = { hint: 'Enter the secret code' }; }}
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_flutter_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 == 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; }};
Note that each of these if/else blocks are referencing event.request.session
. The session is a JS array in which each index represents a step in 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.
Setting-up custom auth flow manually
The custom auth flow can be configured manually.
If you have already configured custom auth without the aid of the Amplify CLI, you can use the custom auth flow by changing the authenticationFlowType
value in your Amplify configuration to CUSTOM_AUTH
.
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.
Because authentication flows in Cognito can be switched via your configuration, it is still required that users register with a password.
Future<void> signUpCustomFlow() async { try { final userAttributes = <AuthUserAttributeKey, String>{ AuthUserAttributeKey.email: 'email@domain.com', AuthUserAttributeKey.phoneNumber: '+15559101234', // additional attributes as needed }; final result = await Amplify.Auth.signUp( username: 'myusername', password: 'mysupersecurepassword', options: SignUpOptions(userAttributes: userAttributes), ); safePrint('Sign up result: $result'); } on AuthException catch (e) { safePrint('Error signing up: ${e.message}'); }}
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.
Future<void> confirmUser({ required String username, required String confirmationCode,}) async { try { final result = await Amplify.Auth.confirmSignUp( username: username, confirmationCode: confirmationCode, ); // Check if further confirmations are needed or if // the sign up is complete. await _handleSignUpResult(result); } on AuthException catch (e) { safePrint('Error confirming user: ${e.message}'); }}
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:
// Create state variables for the sign in statusvar isSignedIn = false;String? challengeHint;
Future<void> signInCustomFlow(String username) async { try { final result = await Amplify.Auth.signIn(username: username); setState(() { isSignedIn = result.isSignedIn; // Get the publicChallengeParameters from your Create Auth Challenge Lambda challengeHint = result.nextStep.additionalInfo['hint']; }); } on AuthException catch (e) { safePrint('Error signing in: ${e.message}'); }}
Confirm sign in with custom challenge
Get the custom challenge (1234
in this case) from the user and pass it to the confirmSignin()
api.
Future<void> confirmSignIn(String generatedNumber) async { try { final result = await Amplify.Auth.confirmSignIn( /// Enter the random number generated by your Create Auth Challenge trigger confirmationValue: generatedNumber, ); safePrint('Sign in result: $result'); } on AuthException catch (e) { safePrint('Error signing in: ${e.message}'); }}
Once the user provides the correct response, they should be authenticated in your application.
Custom authentication flow with password verification
The example in this documentation demonstrates the passwordless custom authentication flow. However, it is also possible to require that users supply a valid password as part of the custom authentication flow.
To require a valid password, you can alter the DefineAuthChallenge
code to handle a PASSWORD_VERIFIER
step:
exports.handler = async (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 = '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; }
return event;};