如何从Postman向GraphQL Mesh传递Bearer Token
我正在为50多个GraphQL端点搭建统一网关,选用了GraphQL Mesh。目前可以在配置中硬编码Token,但生产环境需要传递动态生成的Token。我尝试通过context.headers获取请求头中的Token来配置operationHeaders,但启动网关时出现“AggregateError: Failed on fetching Federated SDL for bff”错误,请问如何正确配置让网关接收Postman等客户端的Bearer Token?
当前可运行的配置
sources: - name: rick-and-morty handler: graphql: endpoint: https://rickandmortyapi.com/graphql - name: trevorblades handler: graphql: endpoint: https://countries.trevorblades.com - name: bff handler: graphql: endpoint: https://teller.com/svc/bff/graphql source: ./sdl.gql operationHeaders: Authorization: Bearer rhuirijjsihjbfejnbsd,ojfjerbfbjihjbefnfnjhiuureiwbanbk transforms: - encapsulate: name: bff applyTo: query: true mutation: true subscription: true
尝试的配置
- name: bff handler: graphql: endpoint: https://teller.com/svc/bff/graphql source: ./sdl.gql operationHeaders: Authorization: Bearer {context.headers['x-my-api-token']} transforms: - encapsulate: name: bff applyTo: query: true mutation: true subscription: true
报错信息
AggregateError: Failed on fetching Federated SDL for bff
at /Users//WebstormPuserrojects/Kyosk-GraphQL-Gateway/node_modules/@graphql-mesh/merger-stitching/cjs/index.js:49:27
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.getWithSet (/Users/user/WebstormProjects/GraphQL-Gateway/node_modules/@graphql-mesh/store/cjs/index.js:167:38)
at async StitchingMerger.replaceFederationSDLWithStitchingSDL (/Users/user/WebstormProjects/GraphQL-Gateway/node_modules/@graphql-mesh/merger-stitching/cjs/index.js:35:25)
错误原因
启动网关时,GraphQL Mesh会自动尝试预获取BFF端点的联邦SDL,但此时还没有用户请求进入,context.headers为空,导致请求BFF时Authorization头无效,直接触发了SDL获取失败的错误。
正确配置步骤
- 跳过SDL预获取:既然你已经通过
source: ./sdl.gql提供了本地SDL文件,就不需要Mesh在启动时从远端拉取,添加skipFetchingSDL: true即可避免这个问题。 - 修正动态头语法:模板字符串需要用双引号包裹,否则YAML解析会出错;同时确保头参数的取值逻辑正确。
修改后的BFF配置如下:
- name: bff handler: graphql: endpoint: https://teller.com/svc/bff/graphql source: ./sdl.gql skipFetchingSDL: true # 关键:关闭启动时的SDL自动拉取 operationHeaders: # 若客户端传递的是标准Authorization头,直接转发即可 # Authorization: "{context.headers['Authorization']}" # 若用自定义x-my-api-token头,按下面的方式拼接Bearer Token Authorization: "Bearer {context.headers['x-my-api-token']}" transforms: - encapsulate: name: bff applyTo: query: true mutation: true subscription: true
特殊场景处理
如果你的BFF端点必须携带Token才能获取SDL,可以单独配置fetchSDLHeaders提供静态Token用于启动时的SDL拉取,同时保留operationHeaders传递用户的动态Token:
graphql: endpoint: https://teller.com/svc/bff/graphql source: ./sdl.gql fetchSDLHeaders: # 仅用于启动时拉取SDL的静态Token Authorization: Bearer <静态SDL访问Token> operationHeaders: # 运行时转发用户的动态Token Authorization: "{context.headers['Authorization']}"
内容的提问来源于stack exchange,提问作者justrying

