【问题标题】:How to query a Strapi backend using GraphQL as an authenticated user?如何使用 GraphQL 作为经过身份验证的用户查询 Strapi 后端?
【发布时间】:2019-09-25 10:21:05
【问题描述】:

目前,我只能以公共用户身份运行查询,Strapi 会为我获取结果。但是,我想完全阻止对公共用户的所有查询访问,只允许经过身份验证的用户(最好只有一个特定用户)。

我知道我可以在 Roles & Permissions 插件中阻止查询访问,而且我也知道可以在 Content Types -> Users 屏幕。其实我已经有了,叫web。现在,我如何以这个特定用户的身份在我的/graphql/ 端点执行查询?

【问题讨论】:

    标签: strapi


    【解决方案1】:

    GraphQL 端点不是通过route 管理的,而是通过中间件管理的。 所以没有应用策略系统。

    您将无法移除对此端点的访问权限。 但是您可以通过更新 GraphQL 配置文件来禁用 GraphQL Playground GET /graphql。这是执行此操作的文档https://strapi.io/documentation/3.0.0-beta.x/guides/graphql.html#configurations

    如果您想限制对 GraphQL 端点的访问,我建议您创建一个新的中间件,该中间件将检查触发的端点是否为 /graphql,并检查经过身份验证的用户是否是您想要的。

    这里是创建中间件的文档https://strapi.io/documentation/3.0.0-beta.x/advanced/middlewares.html

    你的中间件看起来像这样

    module.exports = strapi => {
      return {
        initialize() {
          strapi.app.use(async (ctx, next) => {
            const handleErrors = (ctx, err = undefined, type) => {
              if (ctx.request.graphql === null) {
                return (ctx.request.graphql = strapi.errors[type](err));
              }
    
              return ctx[type](err);
            };
    
            // check if it's a graphql request
            if (ctx.request.url === '/graphql' && ctx.request.method === 'POST') {
              if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
                try {
                  // get token data
                  const { id } = await strapi.plugins[
                    'users-permissions'
                  ].services.jwt.getToken(ctx);
    
                  if (id === undefined) {
                    throw new Error('Invalid token: Token did not contain required fields');
                  }
    
                  // check if the id match to the user you want
                  if (id !== 'my-user-id') {
                    return handleErrors(ctx, 'You are not authorized to access to the GraphQL API', 'unauthorized');
                  }
                } catch (err) {
                  return handleErrors(ctx, err, 'unauthorized');
                }
              } else {
                // if no authenticated, return an error
                return handleErrors(ctx, 'You need to be authenticated to request GraphQL API', 'unauthorized');
              }
            }
    
            await next();
          });
        }
      };
    };
    

    此代码将限制 my-user-id 访问您的 GraphQL API。

    要进行身份验证,您必须在标头中发送 JWT。请按照此处的文档了解它https://strapi.io/documentation/3.0.0-beta.x/guides/authentication.html

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 2020-11-24
      • 2020-11-14
      • 2017-09-11
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2017-03-05
      相关资源
      最近更新 更多