![](/img/trans.png)
[英]Passport Authentication req.isAuthenticated is always false
[英]Passport req.isAuthenticated() always false when deployed to Heroku
我在Nodejs
使用passport
。 當我在本地主機上運行時,我的應用程序按預期工作。 但是,當我部署到Heroku時,我發現req.isAthenticated()
函數在應返回true的情況下返回false,即使通行證正在查找並驗證用戶名和密碼。 這是初始化express-session
和passport
代碼:
app.use(cookieParser());
app.use(session({
secret: 'foo',
resave: true,
saveUninitialized: true,
cookie: {
secure: true,
maxAge: 3600000
//maxAge: new Date(Date.now() + 3600000)
}
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
這是我定義本地護照的方法:
module.exports = function(passport, configIds) {
passport.use('login', new LocalStrategy({
usernameField: "email",
passwordField: "password",
passReqToCallback: true
},
function(req, email, password, cb) {
//console.log('got email pwd: ' + email + ' ' + password);
User.getByEmail(email, function(err, user) {
if (err) {
console.log('something went wrong in login strategy getting user: ' + err);
return cb(err);
}
if (!user) {
console.log('problem with user in local strategy');
return cb(null, false, { message: 'cannot locate user'});
}
if (!User.comparePassword(user, password)) {
console.log('incorrect password for user');
return cb(null, false, { message: 'incorrect email or password'});
}
console.log('success: return the user');
return cb(null, user);
});
}
)),
我正在取得success: return the user
控制台輸出,然后再一次,當我在本地主機上運行時, req.isAuthenticated()
函數返回true,正如預期的那樣。 我看到了一些有關使用https的評論,但是我在localhost和Heroku上都使用了安全套接字。 這是我定義的中間件,用於檢查請求是否已通過身份驗證...
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
next();
} else {
// if they aren't redirect them to the home page
//return res.redirect('/');
console.log('User not authenticated. Redirect to home');
return res.status(401).redirect('/');
}
}
編輯:我還檢查了正在存儲哪些cookie。 我可以看到,以localhost身份運行時,正在存儲會話cookie,但從Heroku運行時不存在任何cookie。
誰能說出為什么可以在本地主機上運行但在Heroku上運行時卻無法運行嗎?
好的,現在可以正常工作了,似乎是因為代理配置沒有正確設置,正如程序員在其中一項注釋中所建議的(謝謝!)。 請參閱下面的修正代碼,以解決問題...
app.use(cookieParser());
app.enable('trust proxy'); // add this line
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
proxy: true, // add this line
cookie: {
secure: true,
maxAge: 3600000,
store: new MongoStore({ url: config.DB_URL })
}
}));
我還添加了MongoStore以保存robertklep建議的會話。 希望這對遇到相同問題的任何人有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.