Authentication Using GraphQL Ruby

Pulkit Goyal
2 min readApr 30, 2021

--

I often get asked questions about how to implement an authentication system for use in a frontend app relying wholly on GraphQL. There are divided opinions on whether you should keep authentication separate from the GraphQL API. To be honest, I don’t see a reason to do that. If you do authentication through a controller reached through a REST API or through the GraphQL Schema, it hardly makes any difference and if the frontend relies heavily on GraphQL, I don’t see a reason not to have the authentication part with it too.

Separating GraphQL Schema

The first thing to handling authentication through GraphQL is serve two different Schemas based on whether the user is making authenticated requests or a non-authenticated one. It is also the simplest one to take care of, so let’s get this out of the way.

If you are using graphql-ruby, you might already have something along the lines of the following in your GraphQLController:

All we need is to provide that schema class based on whether the user is currently logged in. Something like this:

Just define the schema classes as separate classes inheriting from GraphQL::Schema and you are done.

Public Schema and Auth Mutations

The first question we need to ask ourselves is what authentication is in terms of our app? For us, it is a mutation that creates a new UserSession on the backend. So the PublicSchema boils down to a single mutation:

You can add more operations if you need to support sign up, account recovery options etc. But once we can figure out the login part, the rest could be derived pretty easily.

Here’s how it can be implemented easily. Note that we are using authlogic as our authentication system. If you are using something else, only the resolve implementation would change.

Originally published at https://pulkitgoyal.in.

--

--

Pulkit Goyal
Pulkit Goyal

Written by Pulkit Goyal

I am a software developer with a focus on Elixir, Ruby and React. I build things and write stuff.