gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:21:39 25 4
gpt4 key购买 nike

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

  • 向用户提供身份验证 token 的注册和登录用户
  • 创建 map (数据示例:{ name: “Quotes”, attributes: [“quote”, “author"] })
  • 创建 map 项(数据示例:{ 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 Basic Auth 或您想使用的任何机制来获取您的身份验证 token ,然后通过 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);
    });

    然后在架构内,您可以访问您的 rootValue 并可以将其用于访问控制和授权:
    resolve: (parent, args, {rootValue}) => {
    const viewer = {rootValue};

    // Code that uses viewer here...
    }

    请注意,从 graphql v0.5.0 开始, the resolve signature has changed第三个“context”参数已插入到参数列表的第 3 位。此参数适用于传递身份验证 token 或类似的:
    resolve: (parent, args, authToken, {rootValue}) => {
    // Code that uses the auth token here...
    }

    关于api - 如何使用 GraphQL 构建经过身份验证的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952792/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com