NOTE: This example will be using Apollo-Client 1.x and Apollo-Server-Express 1.2.0.
This is part two of my Production GraphQL series. Check out part 1, “Essential Setup and Tooling”, here.
Each field provided by a GraphQL Schema corresponds to a resolver that produces the correct field. This gives us unparalleled control over our API, allowing us to govern access by field rather than HTTP endpoint. Let’s dive into how we do that below.
I prefer JSON Web Tokens for authentication. They’re reusable across all platforms and double as an information exchange. Read more about it here.
To use JWT, you need to send it in the Authorization header in each HTTP request, and decrypt it with a secret on the server. Check out this basic example:
That’s it! When a user with a bad JWT sends a request, your server will return a
401 Unauthorized error.
GraphQL allows us to define each object’s resolvers, which means we can define who has access to certain objects and object fields. First, let’s update our server to pass the user context to each resolver. Update our previous code to look like this:
Now the decoded JWT object will be passed to each object and field resolver and mutator:
Now you can perform authorization at the object level, or govern access to individual fields.
If you enjoyed this article, please help out with a like, a share, or a comment. It fuels my focus to write more of it, thanks!
James Mensch is the Director of Engineering at Threatcare and the CEO at Magnifai. I believe in building intelligent products, using data to drive decisions, and engineering for social impact. I write about some of the cool stuff I do with tech, productivity and motivation psychology, and my social innovation projects. Connect with me on LinkedIn or say hi on Twitter.