0

I am using a JWT token based login system and it is working fine.

But I need to get user details based on JWT token

exports.signin = function(req, res) {
    User.findOne({
        username: req.body.username
    }, function(err, user) {
        if (err) throw err;
        if (!user || !user.comparePassword(req.body.password)) {
            return res.status(401).json({ message: 'Authentication failed. Invalid user or password.' });
        }
        return res.json({ token: jwt.sign({ email: user.email, username: user.username, _id: user._id }, 'RESTFULAPIs') });
    });
};

app.use(function(req, res, next) {
  if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
    jsonwebtoken.verify(req.headers.authorization.split(' ')[1], 'RESTFULAPIs', function(err, decode) {
      if (err) req.user = undefined;
      req.user = decode;
      next();
    });
  } else {
    req.user = undefined;
    next();
  }
});

I also need to set the expiration time.

How can I do that?

jps
  • 20,041
  • 15
  • 75
  • 79
Learning
  • 61
  • 8
  • you could have a look at this detailed [answer](https://stackoverflow.com/questions/46364199/any-complete-example-for-express-jwt/52721909#52721909) – iLuvLogix Nov 14 '18 at 15:47

2 Answers2

0

Ref : NodeJs - Retrieve user infor from JWT token?

exports.me = function(req,res){
    if (req.headers && req.headers.authorization) {
        var authorization = headers.authorization,
            decoded;
        try {
            decoded = jwt.verify(authorization, secret.secretToken);
        } catch (e) {
            return res.status(401).send('unauthorized');
        }
        var userId = decoded.id;
        // Fetch the user by id 
        User.findOne({_id: userId}).then(function(user){
            // Do something with the user
            return res.send(200);
        });
    }
    return res.send(500);
}

Ref: For token expiration / extending it JWT (JSON Web Token) automatic prolongation of expiration Web applications A good pattern is to refresh the token before it expires.

Set the token expiration to one week and refresh the token every time the user open the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.

To refresh the token your API needs a new endpoint that receives a valid, not expired JWT and returns the same signed JWT with the new expiration field. Then the web application will store the token somewhere

Senthil
  • 2,156
  • 1
  • 14
  • 19
  • I try this but I got Authentication fails. Invalid user or password – Learning Nov 14 '18 at 15:50
  • Here you have mentioned as Login works - 'I am using JWT Tocken based Login system so it working fine'. Can you pls share the error details ? add console.log or debug in VC code remote debugging https://code.visualstudio.com/docs/nodejs/nodejs-debugging – Senthil Nov 14 '18 at 15:58
  • Ref full example here http://jasonwatmore.com/post/2018/08/06/nodejs-jwt-authentication-tutorial-with-example-api – Senthil Nov 15 '18 at 02:17
0

Modify Your code as follow:-

exports.signin = function (req, res) {
  User.findOne({
    username: req.body.username
  }, function (err, user) {
    if (err) throw err;
    if (!user || !user.comparePassword(req.body.password)) {
      return res.status(401).json({ message: 'Authentication failed. Invalid user or password.' });
    }
    let NumberOfDayInMiliSec = 1000 * 60 * 60 * 24 * 1 //One Day
    return res.json({ token: jwt.sign({ exp: Date.now() + NumberOfDayInMiliSec, email: user.email, username: user.username, _id: user._id }, 'RESTFULAPIs') });
  });
};

app.use(function (req, res, next) {
  if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
    jsonwebtoken.verify(req.headers.authorization.split(' ')[1], 'RESTFULAPIs', function (err, decode) {
      if (err) req.user = undefined;
      if (decode.exp < Date.now()) {
        return res.status(400).json({ status: false, msg: "Token expired" });
      }
      req.user = decode;
      next();
    });
  } else {
    req.user = undefined;
    next();
  }
});
Abhay Kumar Upadhyay
  • 2,117
  • 1
  • 7
  • 12