I am facing an issue with makeRemoteExecutableSchema.
There is one api gateway graphql/express server(get all the request from clients) and
multiple microservice graphql/express servers(auth, business logic1 , business logic2, business logic3 etc) that are connected to this gateway using schema stitching.(mergeSchema)
if client requests with Bearer token, normally I can retrieve token from headers and use context to pass down authorization token and use it at the resolvers. But How can I pass this to remote server?
It seems like modifying request object doesn't affect anything.(it only affects the object in gateway server)
It seems like copying graphql specific data only and send it to remoteServer.(Therefore, I couldn't get the Authorization header at my remoteServer)
so far, I couldn't find a way to pass my jwt token from api gateway to other remote servers.
Am I thinking something wrong? Please help.
Have you tried creating a middleware?
const service1Fetcher = createApolloFetch({ uri: "..." });
const service1Schema = await makeRemoteExecutableSchema({
schema: await introspectSchema(service1Fetcher),
fetcher: service1Fetcher,
});
service1Fetcher.use(function setHeaders({ options, request: { context } }, next) {
if (context.graphqlContext.jwtToken == null) {
return next();
}
if (options.headers == null) {
options.headers = {};
}
options.headers.Authorization = `Bearer ${context.graphqlContext.jwtToken}`;
next();
});
You must define jwtToken in you GraphQL context so you can access it in fetcher's middleware.
I went through the same issue and indeed, the solution I've found was to define the token within GraphQL context. To do so, I have updated the following line:
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: mergedSchema }))
to
app.use('/graphql', bodyParser.json(), graphqlExpress((req) => ({
schema: mergedSchema,
context: {
authorization: req.headers.authorization
}})))
Passing a function will give you the express request object as an argument. I then use setContext from 'apollo-link-context' like so:
const setTokenContextAsHeader = setContext((_, { graphqlContext: { authorization } }) => {
return {
headers: { authorization }
}
});
I hope this help.
Thanks guys for your help. It is working now.
@krishnasingh87 I seem to be stuck with this too - would you mind sharing your solution?
hello @garydevenay. What about the solution posted above? Do you have any issue with it?
Sounds like this has been resolved via https://github.com/apollographql/graphql-tools/issues/578#issuecomment-361376615 - thanks!
Most helpful comment
I went through the same issue and indeed, the solution I've found was to define the token within GraphQL context. To do so, I have updated the following line:
to
Passing a function will give you the express request object as an argument. I then use
setContextfrom 'apollo-link-context' like so:I hope this help.