I'm trying to create jwt auth with passport-jwt but I'm having a hard time figuring out why the callback is never triggered for the JwtStrategy (auth.passport.js):
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Auth = require('./modules/auth/auth.main');
const User = require('./modules/user/user.main');
const Foo = require('./modules/foo/foo.main');
const config = require('./config/database');
const AuthPassport = require("./modules/auth/auth.passport")();
class App {
// express : require('express')
constructor () {
this.express = express();
this.middleware();
this.database();
this.routes();
}
middleware () {
//this.app.use(logger('dev'));
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: false }));
this.express.use(AuthPassport.initialize());
}
database () {
mongoose.Promise = global.Promise; // use built-in Promise
mongoose.connect(config.address);
}
routes () {
this.express.use('/api/v1/auth' , Auth);
this.express.use('/api/v1/users', User);
this.express.use('/api/v1/foos', AuthPassport.authenticate(), Foo);
}
}
module.exports = new App().express;
auth.passport.js
const passport = require("passport");
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const config = require("../../config/config");
const UserModel = require("../user/user.model");
// refer to: https://github.com/themikenicholson/passport-jwt
module.exports = () => {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.jwt.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log("jwt_payload", jwt_payload); // not being triggered
UserModel.findOne({_id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
return {
initialize: function() {
return passport.initialize();
},
authenticate: function() {
return passport.authenticate("jwt", { session: false });
}
};
};
The console.log that I have inside the callback of the jwt strategy is not being triggered at all (see "// not being triggered" comment) when I send a request to the Foo route, and I'm getting "Unauthorized" every single time.
I'm guessing I'm doing something completely wrong but I can't figure it out.
via FPJ
No comments:
Post a Comment