gpt4 book ai didi

javascript - 需要使用 Passport.js/Node.js 对目录(一页除外)进行身份验证?

转载 作者:行者123 更新时间:2023-11-30 13:05:13 25 4
gpt4 key购买 nike

我是 Passport.js 的新手,但我发现它到目前为止运行良好。我将 Passport 与 passport-local 一起使用。

但是,我想要求对除一页之外的整个目录进行身份验证。所以在我的 Node 服务器中,我像这样提供这个目录(使用 express):

app.use("/admin", express.static(__dirname + "/admin"));

然后我想让用户点击/admin/login.html,所以我想做这样的事情:

app.get('/gb-admin/login.html', function(req, res){ });

然后我想要求对其余部分进行身份验证,所以像这样:

app.get('/gb-admin/*', ensureAuthenticated, function(req, res){});

这是我的 ensureAuthenticated 函数,如果有帮助,供引用:

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/gb-admin/login.html')
}

我该怎么做呢?我一直在无限循环中发送内容并导致浏览器超时。谁能帮忙?

最佳答案

你超时的原因是你不能有一个空的路由处理程序;有一次,您必须要么返回响应,要么将请求交给下一个路由处理程序/中间件。

也就是说,试试这个:

function ensureAuthenticated(req, res, next) {
if (req.path === '/gb-admin/login.html' || req.isAuthenticated()) {
return next();
}
res.redirect('/gb-admin/login.html')
}

app.get('/gb-admin/*', ensureAuthenticated, function(req, res, next) {
next();
});

// the static middleware needs to be declared after the route above, otherwise
// it will take precedence and ensureAuthenticated will never be called.
app.use("/gb-admin", express.static(__dirname + "/admin"));

我不认为有一种方法可以让它与登录页面的单独路由一起工作(除非你真的实现读取 login.html 并在没有路由处理程序的情况下将其发回),因此在 ensureAuthenticated 中间件中检查它。

关于javascript - 需要使用 Passport.js/Node.js 对目录(一页除外)进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15938730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com