我想使用passport-jwt创建自己的策略。根据几个教程,我尝试了以下内容:
// 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}`);
})
我可以通过调用“/ authenticate”来生成JWT并将其设置为标头中的Bearer令牌。但现在,我被困在令牌验证中。当我调用“/”时,我首先无法调试我的函数,因为没有任何东西出现,甚至没有出现控制台日志(所以它就像从未调用过身份验证策略一样,没有输出我的多个console.log)并且它让我“未经授权”
我在这里找到了能够回答我的事情:passport jwt verify callback not called
所以我尝试将bearer替换为jwt,并且我成功地在params.jwtFromRequest中获得了令牌。但仍坚持战略。不幸的是,链接问题中的链接已经死了......
有什么建议吗?