Schema stitching: how to implement headers pass-through? #5241
-
I have a GraphQL server that requires authorization via bearer token. Normally this token is provided by client. That's the code I have at the moment: import { createServer } from 'node:http';
import { buildHTTPExecutor } from '@graphql-tools/executor-http';
import { schemaFromExecutor } from '@graphql-tools/wrap';
import { createYoga } from 'graphql-yoga/typings';
import { stitchSchemas } from '@graphql-tools/stitch/typings';
const makeSchema = async () => {
const executor = buildHTTPExecutor({
endpoint: process.env.MY_URL,
headers: {
authorization: `Bearer ${process.env.MY_TOKEN}`,
},
});
return {
schema: await schemaFromExecutor(executor),
executor,
transforms: [
// My custom transforms
],
};
};
const yoga = await createYoga({
schema: stitchSchemas({
subschemas: [await makeSchema()],
}),
});
createServer(yoga).listen(); With this code I provide the token on the server side and expose unprotected GraphQL server to clients. That's not what I want. I still want API requests to require authorization. Is there any way I can still use the server-side token to build the executor, but still autorize cliend-sider requests using a token provided by clients? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The const makeSchema = async () => {
const initialExecutor = buildHTTPExecutor({
endpoint: process.env.MY_URL,
headers: {
authorization: `Bearer ${process.env.MY_TOKEN}`,
},
});
const runtimeExecutor = buildHTTPExecutor({
endpoint: process.env.MY_URL,
headers: (executorRequest) => {
// Get the original request header from the client call
const authorization =
executorRequest?.context?.request?.headers?.headersInit
?.authorization ?? '';
// Use that header to authorize Energy Core GraphQL requests
return {
authorization,
};
},
});
return {
schema: await schemaFromExecutor(initialExecutor),
executor: runtimeExecutor,
transforms: [
// My custom transforms
],
};
}; But it doesn't seem very elegant because the official docs say:
The problem is that I suppose I'm missing something. |
Beta Was this translation helpful? Give feedback.
Request validation is a different thing and completely unrelated to your situation. Your solution is correct and it is not a workaround because executor and stitching cannot know the shape of your context which is implementation specific.