NodeJS 和 Express 身份验证中间件无法正常运行
NodeJS & Express authentication middleware not functioning correctly
我试图通过在 app.js
和 'using' 中要求对服务器的每个请求 运行 函数 isUserAuthenticated
如此:app.use(authenticate.isUserAuthenticated)
.
我有一个 /authenticate
回调路由,由我们的 SAML 身份提供商发布到它,其中包含验证用户和会话所需的信息。这是我的 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')
和 app.use(authenticate.isUserAuthenticated)
.
需要并使用此身份验证功能
问题:无论 if
语句的什么变体来验证请求中是否存在主题 cookie,都不会触发身份验证检查并且也不会重定向到 IDP 身份验证路由。上面代码中的 console.log
检查返回:
undefined
,以及
{}
.
当我像这样手动使用 isUserAuthenticated
函数时,身份验证在单个路由上工作:router.use('/', isUserAuthenticated, function(req, res, next) {...
,但我正在尝试 在全局范围内使用此函数,所以我不必须在每个路由上手动合并此中间件。
任何 advice/suggestions 将不胜感激。谢谢你。
如果使用 express js,需要在路由器对象上设置一个中间件
router.use(isUserAuthenticated)
别忘了把它放在你的路由文件的顶部。
查看应用级和路由级中间件的区别here
如评论中所建议,
您可以将 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");
})
这将处理所有请求,然后再将它们转发到路由。
我试图通过在 app.js
和 'using' 中要求对服务器的每个请求 运行 函数 isUserAuthenticated
如此:app.use(authenticate.isUserAuthenticated)
.
我有一个 /authenticate
回调路由,由我们的 SAML 身份提供商发布到它,其中包含验证用户和会话所需的信息。这是我的 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')
和 app.use(authenticate.isUserAuthenticated)
.
问题:无论 if
语句的什么变体来验证请求中是否存在主题 cookie,都不会触发身份验证检查并且也不会重定向到 IDP 身份验证路由。上面代码中的 console.log
检查返回:
undefined
,以及
{}
.
当我像这样手动使用 isUserAuthenticated
函数时,身份验证在单个路由上工作:router.use('/', isUserAuthenticated, function(req, res, next) {...
,但我正在尝试 在全局范围内使用此函数,所以我不必须在每个路由上手动合并此中间件。
任何 advice/suggestions 将不胜感激。谢谢你。
如果使用 express js,需要在路由器对象上设置一个中间件
router.use(isUserAuthenticated)
别忘了把它放在你的路由文件的顶部。
查看应用级和路由级中间件的区别here
如评论中所建议,
您可以将 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");
})
这将处理所有请求,然后再将它们转发到路由。