Authentication in Apollo GraphQL + restify

Erika Suárez Valencia
avocoders
Published in
2 min readDec 13, 2017

In our current project we have a backend with GraphQl, Apollo and restify and we needed to include an authentication layer to it.

There were some requirements for the authentication layer:

  • An external service must be used, in our case Auth0.
  • Some information about the user being authenticated (from our database) must be available to use in deeper layers.
  • No global sessions.

As we didn’t want to ask for a token in every query / mutation we had, we decided to include a header on each request to send the authentication token.

Our first solution was to set a middleware on restify, which did its job, but if the authentication fail, the request never reach GraphQl and then the error format were different from other errors, we didn’t want that.

Our final solution was something that behaves similar to a middleware. It was possible thanks to an Apollo graphql-tools function (although it could use an example or a little more explanation): addSchemaLevelResolveFunction.

To explain how to use it let’s start from a very simple schema:

Now we’ll add a function to the schema that will be executed before other resolvers, but only once per request:

Now we only need to pass the token or the headers to our new schema level resolver, suppose our server is like this:

In the code above we are passing a GraphQLOptions object to graphqlRestify. To be able to access the headers on the request we will change that object for a function and add the headers as the context of our GraphQLOptions object.

With that we can authenticate the user on every request and keep the consistency among our error messages.

You can check other ways to do authentication on GraphQl here and here

--

--