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.
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.
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);
})
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With