护照 OAuth Bearer 或 isAuthenticated

Passport OAuth Bearer OR isAuthenticated

我一直在寻找这是否可行,但没有找到任何东西。

基本上我使用 Passport to handle user authentication. Of course using Node.js and Express to handle the server side of things. I'm also using oauth2orize 来允许 OAuth 并处理 API 调用。

对于 API 调用,我使用运行 passport.authenticate('bearer', { session: false }) 的中间件 controllerClient.isBearerAuthenticated。然后关闭并运行 passport.use("bearer", new BearerStrategy) 内的函数。基本上检查令牌是否有效并调用回调函数。

对于非 API 请求和普通网页,它运行以下中间件来检查身份验证。

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/');
}

这是我的问题。如果存在不记名令牌 OR req.isAuthenticated() = true,我想允许访问我的 API 调用。目前我必须选择是使用 isLoggedIn 中间件还是 controllerClient.isBearerAuthenticated 中间件。我正在尝试找到一种方法将它们组合成 or 语句之类的东西。

我正在考虑拥有多个中间件功能,所以它调用 isLoggedIn 然后调用 controllerClient.isBearerAuthenticated。但似乎问题在于回调函数会被调用,所以它们都会被调用。我也在研究是否有一种方法可以跳过下一个中间件功能并转到下一个,但我也找不到任何相关信息。

我认为最好的办法是想办法跳过 controllerClient.isBearerAuthenticated IF req.isAuthenticated() = true。现在可能有更好的方法来做到这一点,如果是的话,我很想听听。

但是关于如何使用中间件检查用户是否通过 req.isAuthenticated() controllerClient.isBearerAuthenticated 授权的任何建议?或者实现这一目标的最佳方法是什么?

One more note. I asked 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 use passport.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 OR controllerClient.isBearerAuthenticated.

提前致谢

我找到了一个似乎有效的解决方案。为了将来参考和可能遇到类似问题的人,我将在下面 post 我的解决方案。

基本上使用以下代码制作一个中间件功能似乎可行。

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。

很高兴弄清楚如何准确地更改 Unauthorized 消息,但希望以后能对此进行调查。