apollo-server - 直接从网关调用实现服务
问题描述
我正在使用 Apollo 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,
};
},
});
一些警告:
- 确保您是否将“可信数据”发送到您的支持服务,“常规客户”无法访问您的支持服务。否则,您将信任可能由不受信任的系统或人员发送的数据。
- 确保你没有在这个函数中做很多繁重的工作,因为你在每个请求上都这样做,无论你的支持服务是否需要它,GraphQL 的价值之一是你永远不会做客户没有特别要求。
推荐阅读
- java - 如何在房间持久性中返回数据的行数
- python - QuantLib-Python:使用 VanillaSwap 仪器的 quantlib Schedule 解决非正时间前向误差
- r - 计算 df2 的几列之间的平均值,该平均值可以根据 df1 的变量 `var1` 变化,并将该值添加到 df1 中的新变量
- pandas - 基于列中的值的示例 Pandas 数据框
- c# - 尝试从 VS 表单应用程序资源加载字体文件时出错
- kubernetes - 从远程计算机访问 kubernetes web ui
- cordova - 如何获取 BarCodeScanner 设备的数据?
- azure - 从 ARM 模板中获取资源组中的 WebApp 列表
- python - 我可以让这段代码更有效率吗?目前运行约 100 万个条目需要约 6 小时
- r - 在 R 中使用 ggplot2 带有下标字符的粗体轴