...

/

Getting Started with GraphQL Authentication

Getting Started with GraphQL Authentication

Learn how to implement authentication in GraphQL.

So far, we’ve only made a few design choices about how we’ll implement authentication. Now, let’s explore implementing a new mutation to authenticate a user and use server-side cookies to send an authentication token to a client making a request.

We’ll implement authentication on the backend. This process can be a bit involved, but we’ll go through it step by step:

  • We define new mutations to log in and log out.
  • We store password information for users in our database. We store password hashes and not the passwords themselves, but we’ll cover this in more detail later.)
  • We implement the login mutation to set a cookie and update our GraphQL server to read a JWT token from an incoming request.
  • We restrict all other mutations to authenticated users.

This is quite a bit to go through, so we’ll implement all the prep work in this lesson and do the remaining steps in the following lessons.

New schema

We’ll start by defining new mutations in our application. We add one mutation to log into our application and another mutation to log out.

Press + to interact
type Mutation {
login(userName: String!, password: String!): LogInResponse!
logOut: Boolean!
}
type LogInResponse {
expiresIn: Int!
user: User!
}

The login mutation receives a username and password, and if the login process succeeds, it’ll set a server-side cookie with a JWT token describing a logged-in user. We don’t need to declare a cookie in a GraphQL schema, but this mutation will return a GraphQL response using the LogInResponse type.

The LogInResponse type contains information about an authenticated user and the JWT token’s expiration time. This might seem like duplication since we can provide the same data in a JWT token in a server-side cookie, but we have to do this ...