Passport JWT JSON Web令牌身份验证错误
我第一次实现了涉及passport和JWT的身份验证。我的问题是:当我在头中发送一个已经过期的令牌时,我会收到消息“Unauthorized”。我的代码如下: 在routes.js中:Passport JWT JSON Web令牌身份验证错误,jwt,passport.js,json-web-token,Jwt,Passport.js,Json Web Token,我第一次实现了涉及passport和JWT的身份验证。我的问题是:当我在头中发送一个已经过期的令牌时,我会收到消息“Unauthorized”。我的代码如下: 在routes.js中: app.route('/people/:id') // .all(function(req, res, next) { // app.auth.authenticate(req, res, next); // }) // .all(app.a
app.route('/people/:id')
// .all(function(req, res, next) {
// app.auth.authenticate(req, res, next);
// })
// .all(app.auth.authenticate)
.all(app.auth.authenticate())
.get(controller.getPeopleById)
.delete(controller.deletePeople);
注释部分是我尝试过的所有部分
在auth.js中:
var passport = require("passport");
var passportJWT = require("passport-jwt");
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
module.exports = function(app) {
const options = {
secretOrKey: app.config.config.jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeader()
};
var strategy = new Strategy(options, function(payload, done) {
console.log("payload: " + JSON.stringify(payload));
});
passport.use(strategy);
return {
initialize : function() {
return passport.initialize();
},
authenticate : function() {
return passport.authenticate('jwt', app.config.config.jwtSession);
// return passport.authenticate('jwt', app.config.config.jwtSession, function(error, done, info) {
// if (error) {
// console.log("error: " + error);
// }
// if (done) {
// console.log("done: " + JSON.stringify(done));
// }
// if (info) {
// console.log("info: " + info);
// }
// });
// }
}
}
};
在middleware.js中:
var bodyParser = require("body-parser");
var config = require("./config/config")();
module.exports = function(app) {
app.set("port", config.port || 3000);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(app.auth.initialize());
};
我所要做的就是捕获身份验证中发生的错误,以自定义消息,例如:“令牌已过期,再次登录”,但实际上,它没有进入策略的验证方法。有人经历过这种情况吗?感激。Passport总是抛出身份验证错误 要获取实际错误,必须提供对passport.authenticate方法的回调 例如:
app.get('/protected', function(req, res, next) {
passport.authenticate('local', function(err, user, failuresOrInfo, status) {
// failuresOrInfo has the cause.
if (err) { return next(err) }
if (!user) { return res.redirect('/signin') }
res.redirect('/account');
})(req, res, next);
});
请参见护照代码中的代码:
function allFailed() {
if (callback) {
if (!multi) {
return callback(null, false, failures[0].challenge, failures[0].status);
} else {
var challenges = failures.map(function(f) { return f.challenge; });
var statuses = failures.map(function(f) { return f.status; });
return callback(null, false, challenges, statuses);
}
}
...
请注意,如果存在回调,passport将结果传递给回调,您必须管理其余部分
希望我的答案是明确的,它可以帮助你