我想用错误信息重定向到登录页面,当有人试图访问我的管理页面而不进行身份验证时,即有人试图绕过登录页面。
这是我的admin端点:
server.get('/admin', isLoggedIn, function (req, res) {
console.log('Trying to access admin section')
res.render('admin', {
user: req.user //get the user out of session and pass to template
})
});它包含以下isLoggedIn中间件:
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
console.log('Someone is trying to access this page without being authenticated')
req.flash('loginMessage', 'You need to be authenticated to access this page');
console.log(req.flash('loginMessage'))
res.redirect('/login')
}login接入点定义如下:
server.get('/login', function (req, res) {
console.log('Using login route');
res.render('login',
{message: req.flash('loginMessage')}
);
});我的问题是,当有人试图直接访问admin页面时,闪存消息就不会出现。但是,当尝试使用假凭据登录时,错误消息确实会显示在登录页面中。有关信息,以下是设置我的post登录路由的方式:
server.post('/login', passport.authenticate('local-login', {
successRedirect:'/admin', // redirect to the secure profile section
failureRedirect:'/login', //redirect back to the login page if there is an error
failureFlash: true //allow Flash messages
}));我在终端机上收到以下信息:
Someone is trying to access this page without being authenticated
[ 'You need to be authenticated to access this page' ]
GET /admin 302 8.859 ms - 68
Using login route
GET /login 200 79.373 ms - 1930发布于 2015-06-06 11:47:00
在connect中,当您使用req.flash(<key>)检索在键上设置的闪存消息时,它会将<key>的消息复制到一个临时数组中,从connect的内部闪存中删除该<key>的消息,然后返回该临时数组。
因此,flash('loginMessage')在路由‘/登录’时返回空,因为您以前在isLoggedIn的console.log(req.flash('loginMessage'))上检索过它。
我查过连接闪存的来源时发现的。在这里:连接闪光灯的flash.js。里面的例子应该很快就能给你这个主意。
发布于 2018-11-09 17:29:38
如果有人来此,而所选的答案不起作用,请考虑尝试以下方法。我也有过同样的问题,但在使用console.log等的任何阶段,我都没有“消耗”密钥。
代码的问题版本如下。我在一条邮政线路上打电话给这些指示:
req.flash('errorMessage', errors.array().map(err => err.msg););
res.redirect('/profile');其中,用于“profile”的GET路由在输入中呈现带有errorMessage: req.flash('errorMessage')的EJS模板。
对我起作用的是将错误消息(errors.array().map(err => err.msg))分配给一个变量,并传递该变量以连接-flash,如下所示:
var errMsgs = errors.array().map(err => err.msg);
req.flash('errorMessage', errMsgs);
res.redirect('/profile');希望这能有所帮助。
https://stackoverflow.com/questions/30657755
复制相似问题