Authentication in GraphQL with Apollo Server 4

Introduction to Authentication in GraphQL

In this lesson, we're diving into how to add authentication to your GraphQL server. Authentication is crucial for securing your API and ensuring that only authorized users can access specific resources. We'll be using Apollo Server, a popular GraphQL server, to implement this. While Apollo Server is widely used for its simplicity and active support, other alternatives include Express-GraphQL and Relay.

Our goal for this lesson is to:

  • Set up an Apollo Server with basic authentication.
  • Implement a login system.
  • Secure certain GraphQL mutations.

Setting Up the Apollo Server

First, let's quickly revise how we set up the GraphQL types and mock data. Our GraphQL server will have two mutations — one for logging in using the provided username and password and another for adding a new book given its author and title.

import { ApolloServer } from '@apollo/server';

const typeDefs = `#graphql
  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book]
  }

  type Mutation {
    login(username: String!, password: String!): String
    addBook(title: String!, author: String!): Book
  }
`;

const users = [{ username: 'admin', password: 'admin' }];
const books = [
  { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien' },
  { id: '2', title: 'Harry Potter', author: 'J.K. Rowling' }
];

Implementing Authentication Logic

Now let's implement the authentication logic to secure our GraphQL API.

For this example, we use a simple array to mock a user database.

const users = [{ username: 'admin', password: 'admin' }];

The login mutation takes a username and password and returns an authentication token if valid.

import { AuthenticationError } from '@apollo/server';

const resolvers = {
  Mutation: {
    login: (_, { username, password }) => {
      const user = users.find(user => user.username === username && user.password === password);
      if (!user) {
        throw new AuthenticationError('Invalid credentials');
      }
      return 'token';
    },
    addBook: (_, { title, author }, { token }) => {
      if (token !== 'Bearer ' + 'token') {
        throw new AuthenticationError('You must be logged in');
      }
      const newBook = { id: '3', title, author };
      books.push(newBook);
      return newBook;
    }
  }
};

Here, we check if the provided credentials match any user in our mock database. If they do, we return a token; otherwise, we throw an AuthenticationError.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal