mysql - NodeJS 从不调用我的承载策略

标签 mysql node.js oauth-2.0 passport.js bearer-token

我尝试通过 Oauth2 和 nodeJS 保护我的 api 端点。我遵循 Oauth2orize 的 Github 页面中提供的所有示例并自定义数据库以检索 MySQL 服务器中的数据。 token 存储在数据库中,与 uid 的用户配置文件相关联。

最后,当我调用我的 URL/api/userinfo 时,我的承载策略没有被调用,我的控制台没有输出(甚至是 console.log)。

请在下面找到代码:

app.get('/api/userinfo', user.info);

exports.info = [
  passport.authenticate('bearer', { session: false }),
  function(req, res) {
    // req.authInfo is set using the `info` argument supplied by
    // `BearerStrategy`.  It is typically used to indicate scope of the token,
    // and used in access control checks.  For illustrative purposes, this
    // example simply returns the scope in the response.
    res.json("Hello")
  }
]

passport.use(new BearerStrategy({},
  function(accessToken, done) {
    console.log("gell");
    db.accessTokens.find(accessToken, function(err, token) {
      if (err) { return done(err); }
      if (!token) { return done(null, false); }
      db.users.find(token.userID, function(err, user) {
        if (err) { return done(err); }
        var info = { scope: '*' }
        console.log(user.cn)
        done(null, user, info);
      });
    });
  }
));

知道为什么没有调用此策略吗?我该如何调试这种情况?

最佳答案

一直以来,让我们回答:

首先,尝试命名你的策略,这就是我所做的:

passport.use('user-bearer', new BearerStrategy(
  function(accessToken, done) {
    jwt.verify(accessToken, config.secrets.session, (err, decoded) => {
      if (err) { return done(null, false, err); }

      // On future, scopes can ve taken from token.
      var info = {
        scope: '*'
      };
      done(null, decoded, info);
    });
  }
));

稍后,您可以像这样验证:

export function isAuthenticated() {
  return passport.authenticate('user-bearer', {
    session: false
  });
}

就我而言,我使用的是无状态 token ,这就是我使用 jwt 网络 token 的原因。

这个isAuthenticated函数是这样使用的:

router.get('/', login.isAuthenticated(), controller.index);

因此,每次调用此路由时都会调用中间件。

也许在您的案例中,您的中间件实现可能没有正确插入到您想要的路由中。

关于mysql - NodeJS 从不调用我的承载策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22931463/

相关文章:

mysql - 组合表或单独表

php - Android- UnknownHostException stumper

node.js - 如何使用node js在ffmpeg中将mp4视频转换为m3u8

javascript - 如何从 node.js 服务器获得简单的响应?

node.js - Nest 恒温器如何通信

php - 如何处理图像 blob 列 mySQL PHP

php - 通过仅填写多个输入字段之一来更新 mysqli 数据库

android - SHA1 指纹已被另一个 OAuth2 客户端使用

java - Spring 安全 OAuth2 样本中的缺陷 : same OAuth2ClientContext used for several providers

javascript - Pocket API 重新尝试授权用户时失败