护照的req.isAuthenticated总是返回false,即使我硬编码(null,true) [英] passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)
本文介绍了护照的req.isAuthenticated总是返回false,即使我硬编码(null,true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经设置了这个中间件:
护照。使用(new LocalStrategy(function(username,password,done){
// return done(null,user);
if(username =='ben'&& password =='benny' ){
console.log(Password correct);
return done(null,true);
}
else
return done(null,false,消息:登录不正确});
}));
但是在这里
app.use('/ admin',adminIsLoggedIn,admin);
函数adminIsLoggedIn(req,res,next){
//如果用户在会话中进行身份验证,则继承
if(req.isAuthenticated())
return next();
//如果他们没有将它们重定向到主页
res.redirect('/');
}
它总是失败并重定向到主页。
我不知道为什么会发生这种情况?为什么不认证?
在我的控制台中,我可以看到这是密码正确
正在打印。
为什么不起作用?
解决方案
我有一个类似的问题。可能是由于护照所需的快速会话中间件。通过以下顺序使用中间件修复它:(Express 4)
var session = require('express-session');
//护照会话需要
app.use(session({
secret:'secrettexthere',
saveUninitialized:true,
resave:true ,
//使用express-session + connect
存储在MongoDB上使用存储会话:new MongoStore({
url:config.urlMongo,
collection:'sessions'
})
}));
//初始护照身份验证
app.use(passport.initialize());
//持久登录会话
app.use(passport.session());
I'm trying to get my Passport local strategy working.
I've got this middleware set up:
passport.use(new LocalStrategy(function(username, password, done) {
//return done(null, user);
if (username=='ben' && password=='benny'){
console.log("Password correct");
return done(null, true);
}
else
return done(null, false, {message: "Incorrect Login"});
}));
but then in here
app.use('/admin', adminIsLoggedIn, admin);
function adminIsLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
it always fails and redirects to the home page.
I can't figure out why this is happening? Why won't it authenticate?
In my console I can see that's Password Correct
is printing.
Why won't it work?
解决方案
I had a similar issue. Could be due to the express-session middleware needed for passport. Fixed it by using middlewares in the following order: (Express 4)
var session = require('express-session');
// required for passport session
app.use(session({
secret: 'secrettexthere',
saveUninitialized: true,
resave: true,
// using store session on MongoDB using express-session + connect
store: new MongoStore({
url: config.urlMongo,
collection: 'sessions'
})
}));
// Init passport authentication
app.use(passport.initialize());
// persistent login sessions
app.use(passport.session());
这篇关于护照的req.isAuthenticated总是返回false,即使我硬编码(null,true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文