I have a GraphQL API (TypeScript, Express, apollo-server), which is being consumed by a client app. All requests require authentication by validating the JWT token like this:
return new ApolloServer({
schema,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
context: async ({ req }) => {
const user = await validateJWT(ctx, req)
return { ...ctx, user }
},
})
(Ignore ctx, it's an implementation specific detail.)
My problem here is that I need to allow a specific query to be unauthenticated. During the onboarding, the client is fetching data before the user is even created.
type Query {
onboardingData(profile: ProfileInput!): OnboardingData!
...
}
What is the appropriate way of bypassing authentication for a particular query?
I've looked into using
import { parse, print } from 'graphql'
to get the query from req.body.query and then do string-matching, but that feels janky, to say the least. My Spidey-senses are tingling that it's prone to errors, confusion and potential vulnerabilities.
In a REST world, I would just specify a particular path to be excluded.
You can get you context to return the function that gets your user, instead of getting the user in the context level and returning it to the resolvers. Wrap your context body in a function and return the function. Then on your resolvers that require authentication and / or the current user, you simply call it, similar to the way you call it in the context body.
Example:
const user = await validateJWT()
Or better named:
const user = await getCurrentUser()
This approach gives you flexibility to only call it on resolvers that require authentication.