首页 > 解决方案 > 直接从网关调用实现服务

问题描述

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

标签: apollo-serverapollo-federation

解决方案


你绝对可以做到这一点。

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 的价值之一是你永远不会做客户没有特别要求。

推荐阅读