1

I'm creating an application learn for my self. So at the moment i need to authenticate an user using with jsonwebtoken and i know how to create a token to authenticate a user. So actually i need to know how can i retrieve logged users's information later by using the token created by the user when logged into the system. i searched everywhere for a good answer but i couldn't find a good answer

apiRoutes.post('/authenticate', function(req, res) {

// find the user
  User.findOne({
    name: req.body.name
  }, function(err, user) {

    if (err) throw err;

    if (!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {

      // check if password matches
      if (user.password != req.body.password) {
        res.json({ success: false, message: 'Authentication failed. Wrong password.' });
      } else {

        // if user is found and password is right
        // create a token
        var token = jwt.sign(user, app.get('superSecret'));

        // return the information including token as JSON
        res.json({
          success: true,
          message: 'Enjoy your token!',
          token: token
        });
      }
    }
  });
});

this is the user login and token creation process

and the below router i need to retrieve all the user information if the user logged into the system and created the token

apiRoutes.get('/users', function(req, res) {
  if(!loggedinUser){
    //throw err
}
else {
  User.find({}, function(err, users) {
    res.json(users);
   });
  });
}

so please help me to understand this and i hope you guys provide me a good answer for this question

thank you

mastercordy
  • 161
  • 1
  • 2
  • 16

2 Answers2

2

Once your authorisation token is generated you need to send that token in all requests through client side. On the the server side you need to implement a authentication middleware in this you will check the authentication token. and process that request further check this link How to use the middleware to check the authorization before entering each route in express?

Aabid
  • 953
  • 5
  • 23
-1

Add User login token in to req.session.token then check it in jwt middle ware .

Zero Day
  • 1
  • 1