I want to use passport-jwt to create my own strategy. According to several tutorial, i tried the following :
// auth.js
const passport = require("passport");
const passportJWT = require("passport-jwt");
const _ = require("lodash");
const users = require("./users.js");
const cfg = require("./config.js");
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
var params = {
secretOrKey: cfg.jwtSecret,
//ignoreExpiration: false,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
//passReqToCallback: false,
jsonWebTokenOptions: {
maxAge: "3 days"
}
};
module.exports = function () {
var strategy = new JwtStrategy(params, function (payload, done) {
console.log('payload received', payload);
// Just check in array is user is on it
var user = users[_.findIndex(users, { id: payload.id })];
if (user) {
return done(null, {
id: user.id,
name: user.name,
scope: user.scope
});
} else {
console.log("Echec : redirection")
return done(new Error("User not found"), null);
}
});
passport.use(strategy);
return {
initialize: function () {
return passport.initialize();
},
authenticate: function () {
return passport.authenticate("jwt", cfg.jwtSession);
}
};
}
// index.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const auth = require("./auth.js")();
const jwt = require("jsonwebtoken")
const users = require("./users.js");
const cfg = require("./config.js");
const moment = require("moment")
const _ = require("lodash");
moment.locale("fr-FR");
var port = process.env.PORT || settings.port || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(auth.initialize());
app.post('/authenticate', function (req, res) {
if (req.body.user && req.body.password) {
var user = users[_.findIndex(users, { user: req.body.user })];
if (user) {
res.set("Authorization", "Bearer " + jwt.sign({
id: user.id,
name: user.name,
exp: Math.round(moment.duration(moment().add(3, 'days').diff(moment())).asSeconds())
}, cfg.jwtSecret))
res.json({
id: user.id,
name: user.name,
type: "Success"
});
} else {
res.sendStatus(401);
}
} else {
res.sendStatus(401);
}
})
app.get('/', auth.authenticate(), function (req, res) {
res.render('trend', {});
})
app.get('/login', function (req, res) {
res.send("Login page")
})
app.listen(port, function () {
console.log(`Example app listening on port ${port}`);
})
I'm able to generate a JWT and to set it in header as a Bearer token, by calling "/authenticate". But now, i'm stuck for the token validation. When i call "/", i'm first not able to debug my function, because nothing appear, even not a console log (so it's like the authentication strategy is never called, none of my multiple console.log is outputted) and it return me "Unauthorized"
I found something that would answer me here : passport jwt verify callback not called
So i tried by replacing bearer to jwt, and i successfully got the token in params.jwtFromRequest. But still stuck for the strategy. And unfortunatelly, the link in the linked question is dead...
Any suggestions ?