Rahul
Rahul

Reputation: 2597

Error: User is not authenticated amazon cognito in nodejs

I am using amazon-Cognito-identity-js and aws-sdk to setup authentication in my nodeJs app.

What i did

First i signup using userpool.signUp(..) method according to docs. Then i confirmed the verification code using cognitoUser.confirmRegistration(..) method according to docs.

Up to here, everything works fine. But, now i would like to get all attributes of the user. I found a method cognitoUser.getUserAttributes(..) which can give me attributes. But when i call this method after cognitoUser.confirmRegistration(..) then it returns Error: User is not authenticated.

I went through a SO question where I got getCurrentUser() will return null at backend side.

So, how can I authorize any user at the fully secured backend side using nodejs?

Upvotes: 5

Views: 7147

Answers (1)

You have to first call the authenticateUser method:

import { CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js'

const authUser = () => {
  const cognitoUser = new CognitoUser({ Username, Pool })
  const authDetails = new AuthenticationDetails({
    Username,
    Password,
  })
  cognitoUser.authenticateUser(authDetails, {
    onSuccess: () => {
      console.log("User authenticated")
    },
    onFailure: (error) => {
      console.log("An error happened")
    },
  })
}

After that, the getCurrentUser method will return the current logged in user. And you will be able to call the getUserAttributes method as well.

Upvotes: 5

Related Questions