【发布时间】:2020-10-21 08:44:16
【问题描述】:
我正在使用 Apollo Federation,我想在网关中实现一些自定义身份验证行为,例如直接从网关调用实现服务以获取用户数据,然后我可以将其添加为标头转发给请求的实施服务。做这样的事情可能吗?这种模式常见还是不推荐?
【问题讨论】:
标签: apollo-server apollo-federation
我正在使用 Apollo Federation,我想在网关中实现一些自定义身份验证行为,例如直接从网关调用实现服务以获取用户数据,然后我可以将其添加为标头转发给请求的实施服务。做这样的事情可能吗?这种模式常见还是不推荐?
【问题讨论】:
标签: 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,
};
},
});
一些注意事项:
【讨论】:
// Do something here to process stuff 部分,我可以向其中一个支持服务发出原始http 请求以获取数据?
viewer 对象的context 函数中执行此操作。那是一个async 函数。 buildService 是一个同步函数,它必须返回一个 GraphQLDataSource。