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

Api 如何使用GraphQL构造经过身份验证的查询?,api,authentication,graphql,Api,Authentication,Graphql,我正在考虑编写一个API,它可以实现以下功能: 向用户提供身份验证令牌的注册和登录用户 创建地图(数据示例:{name:“Quotes”,属性:[“quote”,“author”]}) 创建映射项(数据示例:{quote:“…”,作者:“…”}) 我将构建类似以下内容的查询: // return the name and id of all the user's maps maps(authToken="…") {   name,   id } // return all the item

我正在考虑编写一个API,它可以实现以下功能:

  • 向用户提供身份验证令牌的注册和登录用户
  • 创建地图(数据示例:
    {name:“Quotes”,属性:[“quote”,“author”]}
  • 创建映射项(数据示例:
    {quote:“…”,作者:“…”}
我将构建类似以下内容的查询:

// 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模块,您可以检查cookies或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);
});
然后在模式中,您可以访问您的根值,并可以将其用于访问控制和授权:

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

  // Code that uses viewer here...
}
请注意,从graphql v0.5.0开始,第三个“上下文”参数已插入参数列表中的位置3。此参数适用于传递身份验证令牌或类似信息:

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

我提供了一种方法,将解析器构造为更小函数的组合,以帮助解决这个确切的问题。您可以在这里看到完整的答案:

基本概念是,如果将解析程序构造为组合在一起的小函数,则可以将不同的授权/验证机制层叠在一起,并在第一个机制中抛出一个不满意的错误。这将有助于保持代码干净、可测试和可重用:)

当然,冲突解决程序上下文是存储身份验证信息以及可能需要在整个冲突解决程序中使用的其他功能的好地方

快乐的黑客