gpt4 book ai didi

javascript - NodeJS 和 Express 身份验证中间件无法正常运行

转载 作者:行者123 更新时间:2023-11-30 15:12:21 27 4
gpt4 key购买 nike

我试图通过在 app.js 中要求它并按原样“使用”它来在对服务器的每个请求上运行函数 isUserAuthenticated:app .use(authenticate.isUserAuthenticated).

我有一个 /authenticate 回调路由,由我们的 SAML 身份提供者发布到它,其中包含验证用户和 session 所需的信息。这是我的 authenticate.js 文件中的内容:

module.exports = router;
module.exports.isUserAuthenticated = function(req, res, next) {
console.log(req.cookies.subject);
if (req.cookies.subject) {
console.log(req.cookies.subject)
return next();
} res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
}

如前所述,此身份验证功能在 app.js 中是必需的和使用的:authenticate = require('./routes/authenticate')应用程序使用(authenticate.isUserAuthenticated)

问题:无论 if 语句的什么变体来验证请求中是否存在主题 cookie,都不会触发身份验证检查并且重定向也不会重定向到 IDP 身份验证路由。上面代码中的 console.log 检查返回:

未定义,以及{}

当我像这样手动使用 isUserAuthenticated 函数时,身份验证在单个路由上工作:router.use('/', isUserAuthenticated, function(req, res, next) { ...,但我正在尝试在全局范围内使用此功能,因此我不必在每个路由上手动合并此中间件。

如有任何意见/建议,我们将不胜感激。谢谢。

最佳答案

如评论中所建议,

您可以将 isUserAuthenticated 函数移动到 app.js。它看起来像这样

app.use(function(req, res, next) {
if (req.cookies.subject) {
next();
}
else
res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");

})

这将处理所有请求,然后再将它们转发到路由。

关于javascript - NodeJS 和 Express 身份验证中间件无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44932028/

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