如何使用 GraphQL 构建经过身份验证的查询? [英] How do I structure authenticated queries with GraphQL?

查看:54
本文介绍了如何使用 GraphQL 构建经过身份验证的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑编写一个 API 来执行以下操作:

I was thinking of writing an API that does the following things:

  • 向用户提供身份验证令牌的注册和登录用户
  • 创建地图(数据示例:{ name: Quotes",属性:[quote", author"] })
  • 创建地图项(数据示例:{ quote: "...", author: "..." })

我会像这样构建查询:

// return the name and id of all the user's maps
maps(authToken="…") {
  name,
  id
}

// return all the items of a single map
maps(authToken="…") {
  map(name="Quotes") {
    items
  }
}

// OR by using the map_id
maps(authToken="…") {
  map(id="…") {
    items
  }
}

那么,我的问题是,这是正确的还是我需要以不同的方式构造它?

推荐答案

我建议在 GraphQL 本身之外构建身份验证,并让您的架构逻辑处理授权.例如,如果您使用 express-graphql NPM 模块,您可以检查您的 cookie 或 HTTP 基本身份验证或任何您想用来获取身份验证令牌的机制,然后传递您的身份验证查看器对象通过 rootValue 向下遍历模式,在查询解析期间的每个级别都可用:

I'd recommend constructing authentication outside of GraphQL itself, and letting your schema logic handle authorization. For example, if you are using the express-graphql NPM module, you can check your cookies or HTTP Basic Auth or whatever mechanism you want to use to get your auth token, and then pass your authenticated viewer object down through the schema via the rootValue, which is available at every level during query resolution:

app.use('/graphql', (request, response, next) => {
  const viewer = getViewerFromRequest(); // You provide this.
  const options = {
    rootValue: {
      viewer,
    },
    schema,
  };

  return graphqlHTTP(request => options)(request, response, next);
});

然后在架构内部,您可以访问您的 rootValue,并且可以将其用于访问控制和授权的目的:

And then inside the schema you have access to your rootValue and can use that for the purposes of access control and authorization:

resolve: (parent, args, {rootValue}) => {
  const viewer = {rootValue};

  // Code that uses viewer here...
}

请注意,从 graphql v0.5.0 开始,resolve 签名已更改 和第三个上下文"参数已插入到参数列表中的位置 3.此参数适用于传递身份验证令牌或类似内容:

Note that as of graphql v0.5.0, the resolve signature has changed and a third, "context" parameter has been inserted at position 3 in the argument list. This parameter is suitable for passing down an auth token or similar:

resolve: (parent, args, authToken, {rootValue}) => {
  // Code that uses the auth token here...
}

这篇关于如何使用 GraphQL 构建经过身份验证的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆