mastercordy
mastercordy

Reputation: 161

node js jwt how to pass token to other routes to check logged user information later

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

Upvotes: 1

Views: 2653

Answers (2)

Zero Day
Zero Day

Reputation: 1

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

Upvotes: -1

Aabid
Aabid

Reputation: 941

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?

Upvotes: 2

Related Questions