question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Passwordless Auth with customChallenge (without Amplify)

See original GitHub issue

Which Category is your question related to? Cognito, CustomAuth flow

What AWS Services are you utilizing? Amazon Cognito Identity JS

Provide additional details e.g. code snippets

Hey, I am trying to implement passwordless login with cognito, where user receives a confirmation code via e-mail. The code is randomly generated in the createAuthChallenge lambda.

Following Use case 25 from https://github.com/aws-amplify/amplify-js/tree/master/packages/amazon-cognito-identity-js:

My app client sends a post request tomy backend /login, which triggers the following function:

export const loginUser = (req, res) => {
  const { email } = req.body;

  const poolData = {
    UserPoolId: MY_USER_POOL_ID,
    ClientId: MY_USER_CLIENT_ID
  };
  const userPool = CognitoUserPool(poolData);
  const userData = { Username: email, Pool: userPool };
  const cognitoUser = new CognitoUser(userData);

  const authenticationData = { Username: email };
  const authenticationDetails = new AuthenticationDetails(authenticationData);

  cognitoUser.setAuthenticationFlowType('CUSTOM_AUTH');

  cognitoUser.initiateAuth(authenticationDetails, {
    onSuccess: function(result) {
      console.log('SUCESS', result);
    },
    onFailure: function(err) {
      console.log('ERROR', err);
    },
    customChallenge: function(challengeParameters) {
      let challengeResponse = challengeParameters.ANSWER;
      cognitoUser.sendCustomChallengeAnswer(challengeResponse, this);
      res.json(challengeParameters);
    }
  });
};

The problem is in customChallenge callback - this way I get successfully authenticated, onSuccess callback gets called and tokens are logged to the console. However, I do not want to already automatically sendCustomChallengeAnswer based on challangeParamaters. This should depend on the answer user fills in.

If I would send another post request to /loginwith a code parameter in the request body, then I will always receive an error:

{
   code: 'NotAuthorizedException',
   name: 'NotAuthorizedException',
   message: 'Incorrect username or password.'
}

This happens because the lambda initiates a new session with a new challange Answer code which is not equal to the one im trying to pass in the second POST request.

How can I implement custom auth flow using Amazon Cognito Identity sdk? I do not want to use Amplify.

I also tried this with initiateAuth & respondToAuthChallenge, but then I had an issue with the fact that respondToAuthChallenge() requires a Session parameter which is return by the initiateAuth() method (even though documentation says this is optional) - the Session token is only valid for 3 minutes, so unless there is a way to increase that limit it wont work for my use case:

// Gets triggered when a post request is made to /login:

export const loginUser = (req, res) => {
  const {email} = req.body
    const params = {
      AuthFlow: 'CUSTOM_AUTH',
      ClientId: MY_USER_CLIENT_ID,
      AuthParameters: {
        USERNAME: email
      }
    };

    const identityProvider = new CognitoIdentityServiceProvider();

    return identityProvider.initiateAuth(params, (err, data) => {
      if (err) {
        return next(err);
      } else {
        res.json(data);
      }
    });
  }

// Gets triggered when a POST request is made to /authorize:

  export const respondToChallenge = (req, res, next) => {
  const { username, session, code } = req.body;

  const params = {
    ChallengeName: 'CUSTOM_CHALLENGE',
    ClientId: MY_USER_CLIENT_ID,
    ChallengeResponses: { USERNAME: username, ANSWER: code },
    Session: session
  };

  const identityProvider = new CognitoIdentityServiceProvider();

  identityProvider.respondToAuthChallenge(params, (err, data) => {
    if (err) {
      return next(err);
    } else {
      res.json(
        data.AuthenticationResult
      );
    }
  });
};

Any help or suggestions are very much appreciated, thank you!

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

7reactions
sammartinezcommented, Jun 19, 2019

@KristineTrona There is not currently a way to increase the expiration time. I will mark this as a feature request and bring it to the Service Team’s attention

3reactions
s1mrankaurcommented, Oct 25, 2021

Hi @KristineTrona

“expanding” of the code does work, but not with the intended way. You need to cancel the login flow, even everything works as expected within the first attempt. Save some hash in backend (DynamoDB or something like that) and send the code after the first login attempt and challenge answer.

Now you have the code and information (session + salt or something) on both sides and you can login with those information a second time and answer the challenge with the given code.

This is a hack, but it works.

can you expand on this hack a bit more, please?

“You need to cancel the login flow” - How do I cancel the login flow? "Save some hash in the backend (DynamoDB or something like that) "- Is this hash the hash for the code itself or identified for the user login attempt?

Would be great if you could share a bit more information about it.

@rothalex

@devTechi

Read more comments on GitHub >

github_iconTop Results From Across the Web

Build a Mobile App with Passwordless Login on top of ...
Custom Authentication Challenge with Lambda. In Step 1, the authentication challenge is built and resides in AWS Amplify. In.
Read more >
Authentication - Sign in with custom flow - Swift - Amplify Docs
The Auth category can be configured to perform a custom authentication flow defined by you. The following guide shows how to setup a...
Read more >
Passwordless Authentication with Cognito - DEV Community ‍ ‍
Passwordless Authentication with Cognito · "As a user, I want..." · Cognito Custom Auth · Configuring the Cognito user pool · Verifying an...
Read more >
Passwordless Authentication with Cognito - How to determine ...
This is a workaround by adding a custom attribute during passwordless login. Actually, the authenticationUser function needs to identify ...
Read more >
Build Passwordless Phone OTP Authentication with Cognito ...
In this video we will see how to build Passwordless OTP Authentication with AWS Amplify, Cognito & ReactJS.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found