Search code examples
aws-lambdaamazon-cognitoaws-amplifycustom-authentication

Amplify CUSTOM_AUTH along with username/password is failing with NotAuthorizedException


I am trying to do a username/password login with custom email OTP using CUSTOM_AUTH (amplify js library from a vuejs application)

I have set authenticationFlowType to CUSTOM_AUTH

Below are the steps -

  1. Auth.signIn(username, password)
  2. This executes the first 2 cases of define auth challange lambda trigger
  3. The input json to define auth challange lambda looks like this

{
challengeName: 'SRP_A',
challengeResult: true,
challengeMetadata: null
},
{
challengeName: 'PASSWORD_VERIFIER',
challengeResult: true,
challengeMetadata: null
}

  1. Its clear that password is validated.
  2. It now sets the challange to CUSTOM_CHALLANGE.
  3. At this point the client fails with NotAuthorizedException (Incorrect username or password) instead of asking for the challange answer.

My define auth challange lambda is like this -

exports.handler = async (event, context) => {
console.log(event.request.session)
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 {
console.log('Failing Authentication')
event.response.issueTokens = false;
event.response.failAuthentication = true;
}
context.done(null, event);
}

My question is, is this even supported by amplify? If not then is there any other way?

Documentation referred - https://docs.amplify.aws/lib/auth/switch-auth/q/platform/js#custom_auth-flow

This suggests you to not provide a password but that does not work either.


Solution

  • I found the issue. My create auth lambda was wrong. The if statement in my lambda was if (!event.request.session || event.request.session.length === 0) {

    but should be

    if (event.request.session.length === 2 && event.request.challengeName === 'CUSTOM_CHALLENGE') {

    I had a console.log(event) inside the create auth lambda before the if statement but that was not writing log to cloud watch which led me to believe that the lambda was not getting fired. I created a new lambda function which fixed the logging issue.