Cod*_*ein 36 node.js express passport-local passport.js
我正试图让我的Passport本地策略正常运行.
我已经设置了这个中间件:
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"});
}));
Run Code Online (Sandbox Code Playgroud)
但是在这里
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('/');
}
Run Code Online (Sandbox Code Playgroud)
它总是失败并重定向到主页.
我无法弄清楚为什么会这样?为什么不进行身份验证?
在我的控制台中,我可以看到Password Correct
正在打印.为什么它不起作用?
小智 44
我有类似的问题.可能是由于护照所需的快速会话中间件.通过按以下顺序使用中间件修复它:( 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());
Run Code Online (Sandbox Code Playgroud)
PRA*_*ESE 10
对于新手
我遇到了类似的问题,我的isAuthenticated()函数会返回false.我失去了很多时间,希望这个答案可以保存你的.
一些常见问题需要注意,
这也可能是您客户的POST/GET调用的问题.我有这个完全相同的问题,但事实证明我必须给fetch
(这是我正在使用的)这样的选项credentials:'include'
:
fetch('/...', {
method: 'POST',
headers: myHeaders,
credentials: 'include',
body: ...
...})
Run Code Online (Sandbox Code Playgroud)
原因是因为fetch不支持传递cookie,这在这种情况下是必需的.
我忘记添加也遇到了同样的问题
request.login()
Run Code Online (Sandbox Code Playgroud)
在
app.post('/login',
function(request, response, next) {
console.log(request.session)
passport.authenticate('login',
function(err, user, info) {
if(!user){ response.send(info.message);}
else{
request.login(user, function(error) {
if (error) return next(error);
console.log("Request Login supossedly successful.");
return response.send('Login successful');
});
//response.send('Login successful');
}
})(request, response, next);
}
);
Run Code Online (Sandbox Code Playgroud)
希望这可能会帮助那些和我一样最终在这里的人。
我的问题是即使数据未通过https设置,我也将cookie.secure设置为true。
app.use(require('express-session')({
secret: process.env.sessionSecret,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
},
store: store,
resave: false,
saveUninitialized: false,
cookie: { secure: false } // Remember to set this
}));
Run Code Online (Sandbox Code Playgroud)
如果您不使用https,请记住将cookie设置为false
cookie: { secure: false } // Set to false
Run Code Online (Sandbox Code Playgroud)
另外,如果您确实相信自己有https,请记住信任代理
app.set('trust proxy', 1) // trust first proxy
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30313 次 |
最近记录: |