如何使用GraphQL构建经过身份验证的查询?

Ici*_*cid 13 authentication api graphql

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

  • 注册和登录用户,为用户提供身份验证令牌
  • 创建映射(数据例如:{ name: “Quotes”, attributes: [“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
  }
}
Run Code Online (Sandbox Code Playgroud)

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

win*_*ent 24

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

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

  return graphqlHTTP(request => options)(request, response, next);
});
Run Code Online (Sandbox Code Playgroud)

然后在模式中,您可以访问rootValue,并可以将其用于访问控制和授权:

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

  // Code that uses viewer here...
}
Run Code Online (Sandbox Code Playgroud)

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

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