Allow HTTP401 from "context creation failed" (schema authorization)
See original GitHub issueProblem
Apollo docs suggest doing “schema authorization” in the context function. However, when you throw an AuthenticationError
in the context function, the HTTP status is set to 400
and haven’t found a way to customise this behavior. I’d like a 401 in this situation.
The relevant code can be found from: https://github.com/apollographql/apollo-server/blob/2d1544d049429f979cfcb28c9b83589e23873885/packages/apollo-server-core/src/runHttpQuery.ts#L134-L152
Solution?
Plugins?
Allow a similar solution as described in https://github.com/apollographql/apollo-server/issues/1709#issuecomment-495793375 (requestDidStart + didEncounterErrors)
Customise apollo-server-express behavior?
It seems I should be able to customise behavior at the express<->Apollo level, here: https://github.com/apollographql/apollo-server/blob/bf0cd6b40a639f0453973fdef8c21550b02bb681/packages/apollo-server-express/src/expressApollo.ts#L50-L65
Should full schema auth happen elsewhere?
Different web servers can probably check for auth token / cookie before routing to POST /graphql
Hacky solution for Express
/*
Not included:
- jwt middleware adds req.jwtToken and req.jwtPayload
- apolloServer = new ApolloServer(...)
Note: the order of the three calls here matters.
*/
// before any apollo code, check JWT
app.post('/graphql', (req, res, next) => {
if (!req.jwtToken || !req.jwtPayload || !req.jwtPayload.roles.includes('user')) {
throw new AuthenticationError('unauthorized') // Apollo's error but we could also use our own
}
next()
})
apolloServer.applyMiddleware({ app, path: '/graphql' })
// error middleware that handles AuthenticationError by manually constructing a graphql error
app.use((err, req, res, next) => {
if (err instanceof AuthenticationError) {
res.status(401).send({
data: null,
errors: [
{
message: err.message,
locations: err.locations || [],
extensions: err.extensions || [],
path: err.path || [],
},
],
})
} else {
next(err)
}
})
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:7 (2 by maintainers)
Top GitHub Comments
Same problem here. If we do the authorization during the context creation,
didEncounterErrors
is not calledLinking this to: #3223