护照req.isAuthenticated()始终返回false,而req.user()未定义 [英] Passport req.isAuthenticated() always returning false,and req.user() is undefined
问题描述
我正在使用 passport-facebook 和 express-session 在服务器端存储用户会话. 会话将存储在mongo中,cookie也将在浏览器中设置,但是 req.isAuthenticated()返回false,并且 req.user()未定义.
I am using passport-facebook and express-session for storing sessions of users on the server side. The session is getting stored in mongo,and cookie is also getting set in browser,but req.isAuthenticated() is returning false,and req.user() is undefined.
passport.deserializeUser 也可以正常工作.
关于为什么会发生这种情况的任何想法吗?
Any idea on why this might be happening?
推荐答案
对我来说,这是一个CORS问题.尽管cookie是在浏览器中通过护照正确设置的,但后续的axios请求并未将其发送回去.因此,req.isAuthenticated()和req.user()均无法正常工作.
For me,it was a CORS issue.Though the cookie was properly set in browser by passport,but it was not getting sent back by the subsequent axios requests.So both req.isAuthenticated() and req.user() were not working.
要使其正常运行,我必须在客户端设置以下内容:
To make it work,I had to set the following in client side:
axios.defaults.withCredentials = true;
及以下在服务器端(NodeJS + express):
and following in server side(NodeJS + express):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Credentials",true);
next();
});
这篇关于护照req.isAuthenticated()始终返回false,而req.user()未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!