Pourya8366
Pourya8366

Reputation: 3684

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?

Upvotes: 0

Views: 655

Answers (2)

Pourya8366
Pourya8366

Reputation: 3684

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) {
              ...
           });

Upvotes: 0

Mariusz Wiazowski
Mariusz Wiazowski

Reputation: 2446

Maybe you could try this:

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

Upvotes: 1

Related Questions