GraphQL + PassportJS | AuthN

Rachita Bansal
2 min readSep 23, 2018
Photo by Micah Williams on Unsplash

How to do authentication in GraphQL? This is one of the most common questions developers have when creating a GraphQL application. GraphQL is a graph query language and it doesn’t provide an inbuilt support for things like authentication or authorization. As the GraphQL community is increasing, we are seeing more ways of implementing these. Here are some of the ways a user can access a GraphQL application,

  1. Authentication is handled at the web-server and the request is rejected or redirected by the authentication middleware which means that a logged out user cannot query GraphQL engine.
  2. Authentication is handled by the authentication middleware but the request is resolved via GraphQL resolver. Any user can query GraphQL engine.
  3. Any user can query GraphQL server and authentication is handled via GraphQL itself.

Depending on their use-case one could choose one technique over the other. For e.g., if you are using express.js and Node.js, you could use standard authentication middleware (like Passport.js) and that would take care of the rest for you. Additionally, if you want all requests to be handled through GraphQL, you could add some logic for the request to bypass the authentication middleware and validate the user at GraphQL resolver. If the user is valid, it’s passed to GraphQL’s context else the request gets rejected or redirected by GraphQL as opposed to a standard authentication middleware (like Passpost.js or OAuth). The code would look something like this.

In the above code, the JWT bearer strategy has been used to authenticate a user. Actual authentication logic is moved out to authentication.js for simplicity. It’s important to note in the above code that the callback from Passport.js is not blocked from if an error occurs, it’s passed to GraphQL HTTP middleware instead.

GraphQL middleware would look like this,

That’s it! You can now check if the user is present in the context or not before resolving any request. If the user is not present you can simply throw an error via GraphQL. An example resolver code is given below.

You can also extract this logic out of the resolver and create your own middleware with custom error messages which can then be used for everywhere else in the app.

Ultimately, it’s up to you how you want to handle auth in your GraphQL app. I do user authentication using a separate non-GraphQL endpoint. Once a user is authenticated, it verifies that a particular user has valid roles which is part of authorization logic. All my requests are handled via GraphQL.

--

--

Rachita Bansal

Software Engineer @ Microsoft | Full-Stack | Data viz| Node.js | React | GraphQL | UI/UX