Jer*_*uff 5 authentication infinite-loop node.js express passport.js
我正在尝试使用 express 在 node.js 服务器上设置护照本地身份验证。看起来它应该非常简单。但我被卡住了。
这两个片段可以很好地协同工作:
app.get('/', ensureAuthenticated, function(req, res){
res.redirect('/index.html', { user: req.user });
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login.html', failureFlash: true, successFlash: "Success!" }),
function(req, res) {
res.redirect('/');
});
Run Code Online (Sandbox Code Playgroud)
问题是没有什么可以阻止我在地址栏中键入“www.myurl.com/index.html”并直接放到我的页面上。
如果我使用这样的任何代码:
app.get('/index.html', ensureAuthenticated, function(req, res){
res.redirect('/index.html', { user: req.user });
});
Run Code Online (Sandbox Code Playgroud)
似乎我陷入了循环……如果它可以检查我的身份验证并将我发送给我,而无需永远检查每个重定向,那就太好了。避免这种情况的方法是什么?
我注意到文档似乎使用了 .render,而不是重定向。但这似乎要求我使用 .ejs,我不想这样做。这是必须的吗?
++参考++
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login.html')
}
Run Code Online (Sandbox Code Playgroud)
所以我猜你正在让处理和 的express.static()请求?在这种情况下,您可以创建一个路由,首先检查身份验证,然后采取相应的操作:
index.htmllogin.htmlindex.html
app.get('/index.html', ensureAuthenticated, function(req, res, next) {
// if this block is reached, it means the user was authenticated;
// pass the request along to the static middleware.
next();
});
Run Code Online (Sandbox Code Playgroud)
确保在添加到中间件堆栈之前express.static声明上述路由,否则它将被绕过(Express 中间件/路由按声明顺序调用,第一个匹配请求的将处理它)。
编辑:我一直忘记这是可能的,而且也更干净:
app.use('/index.html', ensureAuthenticated);
Run Code Online (Sandbox Code Playgroud)
(而不是app.get上面的)
| 归档时间: |
|
| 查看次数: |
4302 次 |
| 最近记录: |