0
votes

I have this middle-ware function which checks if the user is logged in or not, since I have web application and android platform as well therefore I am using tokens for the android and for web I am using session which is by default manager by passport.

In my function I am checking If I have a Authorization header, I know it's my android platform and therefore verify user by verifying jwt token, but It is always sending me 401 unauthorized and not setting the req.user.

Here is the middle-ware function, if someone can please point out my mistake where I am going wrong in my logic.

var jwt_auth = require('express-jwt')

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    if (req.get("Authorization")) {
        jwt_auth({secret: 'somesecret'});
        if (req.user) {
            return next();
        }
        res.send(200, "Unauthorized access");
    }
    else {
        // if user is authenticated in the session, carry on
        if (req.isAuthenticated())
            return next();

        // if they aren't redirect them to the home page
        res.redirect('/');
    }
}
1
How are you setting jwt token on client side ?Mukesh Sharma
I am sending the jwt token in Authorization headers from client side with every request,warl0ck

1 Answers

2
votes

That's because jwt_auth is an async action and your res.send(200, "Unauthorized access") never wait for jwt_auth to complete.

You should take a look at express-jwt's example.

The basic one is

var jwt = require('express-jwt');

app.get('/protected',
    jwt({secret: 'shhhhhhared-secret'}),
    function(req, res) {
        if (!req.user.admin) return   res.sendStatus(401);
       res.sendStatus(200);
});

if you want to pass a custom function to extract token from request, use the getToken option, the following example is taken from express jwt's README, you can modify the function in your needs.

app.use(jwt({
  secret: 'hello world !',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
      return req.query.token;
  }
    return null;
  }
}));