我的护照中间件无法使用。当我在路由上调用passport.authenticate()以确认用户已通过身份验证时,我被重定向到失败页面。然而,登录路由按预期工作,并且我被成功重定向到正确的页面,其中调用了故障中间件重定向并且我被发送回登录页面。
我有这样的Passport策略:
module.exports = function(){
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy
var User = require('../models/user');
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: "email",
passwordField: "password"
}, function(email, password, done){
User.getUserByEmail(email, function(err, user){
if(err) throw err;
if(!user){
console.log('unknown user');
return done(null, false, {message: 'Email not recognised, please try again'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid password');
return done(null, false, { message: 'Password not recognised, please try again' });
}
});
});
}));
};
使用以下方式登录很好:
router.post('/user/login',
passport.authenticate('local', {
successRedirect: '/clients',
failureRedirect: '/user/login',
failureFlash: true
}
));
我的'/ clients'路由是这样的,身份验证失败并错误地重定向回登录页面:
router.get('/clients',
passport.authenticate("local", {
failureRedirect: "/user/login",
failureFlash: "not verified"
}), function(req, res, next) {
res.locals.client = null;
Client.find({})
.select("name")
.select("_id")
.exec(function(err, clients){
res.render('client/views/clients', {
title: 'Clients',
clients: clients
});
});
});
服务器护照初始化如下:
//passport
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
require("./user/services/passport")(passport);
我做错了什么?
答案 0 :(得分:0)
因为您使用了failRedirect:'/ user / login'。它会将您重定向到登录页面。如果要将其重定向到另一个页面,请将failureRedirect值更改为相应的路由。