This is part two of my Production GraphQL series. Check out part 1, “Essential Setup and Tooling”, here.

NOTE: This example will be using Apollo-Client 1.x and Apollo-Server-Express 1.2.0.

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.

Authentication

I prefer JSON Web Tokens for authentication. They’re reusable across all platforms and double as an information exchange. Read more about how to use JWTs here.

Authenticating a user with JWTs is straightforward. Include the JWT in the authorization header of each HTTP request, then decrypt it with the corresponding secret on the server. If it decrypts successfully, you’re good to go! Check out this basic example:

That’s it! If decryption fails, your server will return a 401 Unauthorized error.

GraphQL allows us to define how each field resolvers, which means we can get pretty granular authorization. The first thing we need is to pass the decrypted user object (from the user’s JWT) to each resolver. We’ll use Apollo Server’s context field for that. Update our previous code to look like this:

Now the decrypted JWT object will be passed to each object and field resolver and mutator. Check it out:

Now you can perform authorization at the object level, or govern access to individual fields.