In express-jwt is there any way option similar to req.isAuthenticated() similar to passportjs?

691 Views Asked by At

I want to find whether the user is authenticated 'jwt' inside middleware. Is there any way like req.isAuthenticated() similar to passportjs?

module.exports = function(app){
 return function(req, res, next){
  
        // How to implement the below step?
  var isAuthenticated = app.use(jwt({secret: app.get('jwtTokenSecret')}))
        
        if(isAuthenticated){
          // do some logic
        }
            
    }
}

1

There are 1 best solutions below

0
On

Yes there is!

1) You can use use the express-jwt module. Check out https://github.com/auth0/express-jwt

2) You can do it this way:

  //get the authorization token from the request headers, or from a cookie
  if (req.headers && req.headers.authorization) {
    var parts = req.headers.authorization.split(' ');
    if (parts.length == 2) {
      var scheme = parts[0];
      var credentials = parts[1];

      if (/^Bearer$/i.test(scheme)) {
        token = credentials;
      }
    }
  }
  else if(req.cookies && req.cookies.token)
  {
    token = req.cookies.token;
  }
...
  jwt.verify(token, config.secrets.session, function(err, decoded) {
     //isAuthenticated is in here
  });