I want that I can acess 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.
2 Answers
Answers 1
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); }) }
Answers 2
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.
0 comments:
Post a Comment