我尝试登录时成功调用了我的回调,收到了SUCCESS
消息。但我仍然重定向到登录页面。
passport.use(new LocalStrategy(
function(username, password, done) {
console.log(username + "----" + password)
if(username == "test" && password == "test"){
console.log("SUCCESS")
done(null, { name: username})
}
else{
done(null, false)
}
}))
我的路线按下一个顺序定义
.. some othe initialization, cookieparser, bodyparser, session ...
app.use(passport.initialize())
app.use(passport.session())
app.use('/login', login);
app.post('/login',passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/plans');
});
app.all('*',function (req, res, next) {
console.log(req.isAuthenticated())
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login')
})
app.use('/', index);
app.use('/users', users);
app.use('/plans', plans);
这里有错吗?感谢。
答案 0 :(得分:1)
可能的原因可能如下:
在我的节点应用程序中,我有以下中间件:
app.use(session({
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: true,
cookie: { httpOnly: true, secure: true }
}));
以下行始终返回false:
req.isAuthenticated()
当我将安全值从true更改为false时。问题消失了。
答案 1 :(得分:0)
这可能是一个黑暗的镜头,但你需要在failureRedirect之上的successRedirect吗?我认为你正在被正确处理,但是路由然后不知道在成功之后该做什么,所以它只是默认为可用的任何路径。正如我所说,这是一个猜测但似乎有道理。
让我知道。
只是为了展示护照文件中的一个例子:
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
此外,如果您想要进行身份验证,然后让它进入您传入的实际路由功能,那么我认为您想要一起删除重定向。
app.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.redirect('/users/' + req.user.username);
});
同样来自文档。
最佳, Runner5