【问题标题】:Directly calling implementing service from the gateway直接从网关调用实现服务
【发布时间】:2020-10-21 08:44:16
【问题描述】:

我正在使用 Apollo Federation,我想在网关中实现一些自定义身份验证行为,例如直接从网关调用实现服务以获取用户数据,然后我可以将其添加为标头转发给请求的实施服务。做这样的事情可能吗?这种模式常见还是不推荐?

【问题讨论】:

    标签: apollo-server apollo-federation


    【解决方案1】:

    你绝对可以做到。

    const gateway = new ApolloGateway({
      serviceList,
      buildService({ url, name }) {
        // Do something here to process stuff. If you're using RemoteGraphQLDataSource:
        return new RemoteGraphQLDataSource({
          url,
          name,
          willSendRequest({ request, context }): void {
            // This `context` is the object you're returning "down there"
            // Add content to your request
            if (context.viewer) {
              request.http.headers.set('something', 'data');
            }
          },
        });
      },
    });
    
    const server = new ApolloServer({
      gateway,
      // { req, res } is used for apollo-server (or apollo-server-express)
      // { event } is used for apollo-server-lambda
      context: async ({ req, res }) => {
        const authHeader = req.headers.Authorization', '');
        const accessToken = authHeader.replace(/Bearer /, '');
        const viewer = await someAsyncSomethingToGetTheUserData({ accessToken });
    
        // this is the `context` object you use "up there"
        return {
          viewer,
        };
      },
    });
    

    一些注意事项:

    1. 如果您将“可信数据”发送到您的支持服务,请确保“常规客户”无法访问您的支持服务。否则,您将信任可能由不受信任的系统或人员发送的数据。
    2. 确保您没有在此功能中做很多繁重的工作,因为您在每个请求上都这样做,无论您的支持服务是否需要它,而 GraphQL 的价值之一是您从不做客户没有特别要求的工作。

    【讨论】:

    • 那么在// Do something here to process stuff 部分,我可以向其中一个支持服务发出原始http 请求以获取数据?
    • 不,@DavidBrown 我会在创建viewer 对象的context 函数中执行此操作。那是一个async 函数。 buildService 是一个同步函数,它必须返回一个 GraphQLDataSource。
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多