Auth Setup

Tutorial 2 of 4

1. Introduction

1.1 Tutorial's Goal

This tutorial aims to guide you through the process of setting up authentication for your GraphQL application. It will equip you with the knowledge of various authentication methods and how to implement them effectively.

1.2 Learning Objectives

By the end of this tutorial, you should be able to:

  • Understand the importance of authentication in GraphQL applications
  • Implement basic and JWT authentication
  • Handle errors and exceptions during authentication

1.3 Prerequisites

Before you begin, it's important to have a basic understanding of GraphQL and Node.js. Familiarity with JavaScript is also a must.

2. Step-by-Step Guide

2.1 Basic Authentication

Basic authentication is a simple authentication scheme built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the word Basic followed by a space and a base64-encoded string username:password.

Let's start by installing the necessary dependencies. Open your terminal and run:

npm install graphql express express-graphql bcryptjs jsonwebtoken

Now, let's create a simple GraphQL server:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));

app.listen(4000, () => console.log('Server Running'));

2.2 JWT Authentication

JWT (JSON Web Tokens) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

Let's now setup JWT authentication:

const jwt = require('jsonwebtoken');

const authenticate = (req) => {
  const token = req.headers.authorization;
  try {
    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (e) {
    throw new Error('Authentication token is invalid');
  }
};

app.use((req, res, next) => {
  req.user = authenticate(req);
  next();
});

3. Code Examples

3.1 Example 1: Basic Authentication

const bcrypt = require('bcryptjs');

// User data
const users = [
  { id: 1, username: 'user1', password: bcrypt.hashSync('pass1', 10) },
  { id: 2, username: 'user2', password: bcrypt.hashSync('pass2', 10) },
];

// Find user by credentials
const getUser = (username, password) => 
  users.find(user => user.username === username && bcrypt.compareSync(password, user.password));

// In your resolver
const login = (args) => {
  const user = getUser(args.username, args.password);
  if (!user) throw new Error('Invalid credentials');

  // User found
  return { token: jwt.sign({ id: user.id }, process.env.JWT_SECRET) };
};

3.2 Example 2: JWT Authentication

// In your resolver
const getUserPosts = (args, req) => {
  // Not authenticated
  if (!req.user) throw new Error('You must be logged in');

  // Get posts of the user
  return getPostsByUserId(req.user.id);
};

4. Summary

We've covered a lot in this tutorial. We've learned the importance of authentication and how to set up basic and JWT authentication in a GraphQL application. We also learned how to handle errors during the authentication process.

Next steps would be to learn about authorization and how to protect your GraphQL API from malicious queries. Check out the official GraphQL documentation and the JSON Web Tokens website for more information.

5. Practice Exercises

5.1 Exercise 1: Basic Authentication

Implement a register resolver that takes a username and password, hashes the password, and stores the user in memory.

5.2 Exercise 2: JWT Authentication

Implement a logout resolver that invalidates the current user's token.

5.3 Exercise 3: Error Handling

Enhance your authentication middleware to return a specific HTTP status code when authentication fails.

Solutions

For solutions and more practice exercises, check out the official GraphQL documentation and the JSON Web Tokens website.

Remember that the key to mastering GraphQL authentication is practice and consistency. Happy coding!