Pourya8086 Pourya8086 - 3 months ago 45
Node.js Question

passport.authenticate does not execute on a route

I use Passport-jwt Strategy for authentication in express project,

here is mt passport-jwt config in this directory: /config/passport.js



var JwtStrategy = require('passport-jwt')
.Strategy,
ExtractJwt = require('passport-jwt')
.ExtractJwt;

var User = require(__dirname + '/../models/user');
var config = require(__dirname+ '/database');

module.exports = function(passport) {
console.log("here: passport-jwt");
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({
id: jwt_payload.id
}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};





and in account route in /routes/account.js directory i call it this way:

var passport = require('passport');
require(__dirname + '/../config/passport')(passport);

router.post('/', passport.authenticate('jwt', {
session: false
}), function(req, res) { ... }


but the problem is passport function for authentication does not execute. and "here: passport-jwt" did not shown.

where is the problem?

Answer

First of all in app.js, routes must be declared like this:

after adding these lines:

var passport = require('passport');  
app.use(passport.initialize());

you should add these lines:

var account = require(__dirname + '/routes/account')(app, express, passport);
app.use('/account', account);

and in the route itself:

module.exports = function(app, express, passport) {

    var router = express.Router();

    router.post('/', function(req, res) {

        passport.authenticate('jwt', function(err, user) {
        if (err) {
                res.sendStatus(406);
            } else {
                if (!user) {
                    res.sendStatus(400);
                } else {...}
            }
       });
        }

    }
}

my mistake was that is put console.log("here: passport-jwt"); in the first line of module, but in fact passport.use(..) part executing every time!

and the last thing was the findOne part in passport config, passport.use(...) part, when you want to use native id in MongoDB, you should query _id instead of id!

So, the correct code is:

User.findOne({
            _id: jwt_payload.id
        }, function(err, user) {
              ...
           });
Comments