我一直在寻找这是否可行,但没有找到任何东西。
基本上我正在使用 Passport处理用户身份验证。当然,使用 Node.js 和 Express 来处理服务器端的事情。我也在使用oauth2orize允许 OAuth 并处理 API 调用。
对于 API 调用,我使用运行 passport.authenticate('bearer', { session: false })
的中间件 controllerClient.isBearerAuthenticated
。然后就会开始运行 passport.use("bearer", new BearerStrategy)
内部的函数。基本上检查 token 是否有效并调用回调函数。
对于非 API 请求和普通网页,它会运行以下中间件来检查身份验证。
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
这就是我的问题。如果存在不记名 token OR req.isAuthenticated()
= true,我希望允许访问我的 API 调用。目前我必须选择是否要使用 isLoggedIn
中间件或 controllerClient.isBearerAuthenticated
中间件。我正在尝试找到一种方法将它们组合成一个 or 语句或其他东西。
我正在考虑拥有多个中间件函数,因此它调用 isLoggedIn
然后调用 controllerClient.isBearerAuthenticated
。但问题似乎是回调函数会被调用,所以它们都会被调用。我还在研究是否有一种方法可以跳过下一个中间件功能并转到下一个,但我也找不到任何相关内容。
我认为最好的选择是找到一种方法来跳过 controllerClient.isBearerAuthenticated
IF req.isAuthenticated()
=真的。现在可能有更好的方法来做到这一点,如果是的话,我很想听听。
但是有关如何使用中间件检查用户是否通过 req.isAuthenticated()
OR controllerClient.isBearerAuthenticated
进行授权的任何建议>?或者实现这一目标的最佳方法是什么?
One more note. I asked this question before and figured out that
passport.authenticate
is meant to handle the actual authentication not users that have already been authenticated. Otherwise I would just usepassport.authenticate
with an array of Passport strategies. And using connect-ensure-login would have the same issue as I have right now about using connect-ensure-login ORcontrollerClient.isBearerAuthenticated
.
非常感谢提前!
最佳答案
我找到了一个似乎有效的解决方案。为了供将来引用和可能遇到类似问题的人使用,我将在下面发布我的解决方案。
基本上,使用以下代码制作一个中间件功能似乎可行。
function isAuthenticated(req, res, next) {
//Checking to see if user is authenticated on the web
if (req.isAuthenticated()) {
return next();
}
//If not checking to see if user is authenticated via Bearer and OAuth
else {
return controllerClient.isBearerAuthenticated.apply(this, arguments);
}
}
所以我们只是检查req.isAuthenticated
是否等于true。如果是,我们只返回回调函数,并且 API 函数将被调用。如果没有,那么我们检查controllerClient.isBearerAuthenticated
,它会自动调用下一个函数,看起来如果成功的话。如果不是,它将发送 Unauthorized
,状态代码为 401。
很高兴弄清楚如何准确更改未经授权
消息,但希望以后能对此进行研究。
关于javascript - Passport OAuth 持有者或 isAuthenticated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537717/