Session / 自定义 KeystoneJS 端点中的令牌验证

Session / token verification in custom KeystoneJS endpoint

我正在使用概述的方法 here.

成功验证用户对我的 KeystoneJS API 的请求

但是我需要向我的应用程序添加一个自定义的 express 端点,它应该只能供在请求中具有有效令牌的用户访问 header ()。

我一直在深入研究关于 sessions 和中间件的 Keystone 文档,但这不是我的专业领域,我无法弄清楚如何验证请求令牌。

如何在对自定义端点的 GET 请求的授权 header 中验证令牌?感谢这可能与快速和 session 管理有关,而不是专门针对 Keystone。

假设是标准设置,可以将以下内容添加到 configureExpress(参见 here)以将 Keystone 会话中间件应用于自定义 express 端点:

app.use('/myEndpoint', keystone._sessionManager.getSessionMiddleware({ keystone }));

然后:

const whitelist = ['http://localhost:4200'];
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.post('/myEndpoint', cors(corsOptions), (req, res) => {
  if (req.user) {
    // User is authorised
    res.send(req.user);
  } else {
    res.status(401).send()
  }
});

注意事项/陷阱:

  • 您的 POST 请求必须包含一个 GraphQL 查询以验证您的用户
  • 必须正确配置 CORS 选项
  • 还必须提供 sessionStore - 请参阅 here