I’m developing an express app and experimenting with graphql. I’ve started to not using old endpoints I made before. The problem is some of my old endpoints protected by middlewares like:
router.get(
"/",
[auth.verifyToken, auth.checkRole(["role1", "role2"])],
someController.getAllThings
);
So my question is how to protect queries and mutations with middlewares?
1 Answer
In graphql you usually have a single endpoint where your graphql server is running and you provide a context function to your server that is invoked for every incoming request. This is where you can perform authentication/authorization. The context function is passed a request
object that you can use to verify token and check for user roles. The result of this context function is available to all the resolvers so you can decide which queries or mutations need to protected.