Skip to content

Instantly share code, notes, and snippets.

@jakangah
Created February 7, 2019 16:40
Show Gist options
  • Save jakangah/f5c569e539d57ae21d70786571af45a5 to your computer and use it in GitHub Desktop.
Save jakangah/f5c569e539d57ae21d70786571af45a5 to your computer and use it in GitHub Desktop.
Implementing custom authorization when using express-graphql
# We accomplish this by passing the req and res objects from the expressjs router to the context option
# After getting the specific role or permission from the query instance we can accomplish route validation
let graphQLSchema = {
......
resolve: async function(root, args, context){
context.role = 'ADMIN'
}
}
app.use('/public', graphqlHTTP((req, res) => ({
schema: graphQLSchema,
graphiql: true,
pretty: true,
context: { req, res },
extensions ({ document, variables, operationName, result, context }) {
# over here we use which ever validation method we prefer to validate the user request either through the header token or body
let userRole = validateUserByToken(req.headers['token'])
let routeRole = context.role;
if(userRole === routeRole){
# continue as normal
return result
}else{
# user not permitted so return an error message
return {
status : 401,
message : "Forbidden"
}
}
}
})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment