Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route available with or without token JWT+PASSPORT

I want that I can access a router with or without a token. If user has a token, than give me req.user

Like this:

router.get('/profile', function(req, res) {
if(req.user) { // or if (req.isAuthenticated())
 res.send('logged')
} else {
 res.send('not loggedIn')
}
});

My app:

var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = 'sh';
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.sub}, function(err, user) {
    if (err) {
        return done(err, false);
    }
    if (user) {
        done(null, user);
    } else {
        done(null, false);
        // or you could create a new account
    }
});
}));

If I try to access /profile without a token, works fine. But, when a try to access /profile with a token in header give me not loggedIn

I want to access it even without a token and, if I provided a toke, give me the user.

ps: Already tested using passport.authenticate('jwt') in route and works. If I give token let me access, if not give me unauthorized.

like image 864
Igor Martins Avatar asked Jan 20 '17 03:01

Igor Martins


3 Answers

This is how I'm doing it:

const passport = require('passport');

const optionalJwt = function (req, res, next) {
  if (req.headers['authorization']) {
    return passport.authenticate('jwt', { session: false })(req, res, next);
  }
  return next();
};

app.get('/my/route', optionalJwt, function (req, res, next) {
  if (req.isAuthenticated()) {
    res.send('My name is ' + req.user.name);
  } else {
    res.send('I\'m not authenticated :(');
  }
});

It will still fail if the auth header is included but the token has expired or it's invalid, but it might serve the purpose. For me it did.

like image 162
javorosas Avatar answered Nov 15 '22 05:11

javorosas


Change you router as follows

router.get('/profile', authenticateUser(), profile());

function authenticateUser(req, res, next) {
  // your strategy here...
  if (authenticated) { 
    req.user = user;
    next();
  } else {
    return res.status(401).send("Not authenticated");
  }
}

function profile(req, res, next) {
  var userId = req.user.id;
  User.findById(userId, function(err, user) {
    if (err) { return res.status(500).json(err); }
    return res.json(user);
  })
}
like image 38
Adeeb basheer Avatar answered Nov 15 '22 05:11

Adeeb basheer


you should be using one of the below to access request data

if (req.params.user) {do something...}

or

if (req.body.user) {do something...}

the request object has no user attribute.

like image 38
LostJon Avatar answered Nov 15 '22 05:11

LostJon