Learn GraphQL Β· 9/15

Security: Authentication & Authorization

8 min read

πŸ›‘οΈ Security: Authentication & Authorization in GraphQL

Welcome, intrepid GraphQL explorer! You've learned how to build schemas, fetch data, and perform mutations. Now it's time to put on our security hats and learn how to protect our precious API from unauthorized access. It's like building a fantastic new theme park; you need to have ticket booths and ride operators to ensure everyone has a safe and enjoyable experience.

In the world of APIs, we have two fundamental security concepts: Authentication and Authorization. They might sound similar, but they play very different, and equally important, roles.

  • Authentication is the process of verifying who a user is. ამო Think of it as the friendly security guard at the entrance of our theme park checking your ticket to make sure it's valid.
  • Authorization is the process of determining what an authenticated user is allowed to do. 🎟️ Once you're inside the park, your ticket might grant you access to certain rides but not others (like the super-scary, "you must be this tall" roller coaster).

Confusing these two is a classic security slip-up. Just because you know who someone is, doesn't mean they should have the keys to the entire kingdom!


1. Authentication: Identifying the User via Headers & Context πŸ•΅οΈβ€β™€οΈ

The Problem: How does our GraphQL server know who is making a request? By default, all requests are anonymous. We need a way for users to present their "ticket" or credentials with every request they send.

The Solution: Headers and Context

The most common way to handle authentication in GraphQL is by using HTTP headers. When a user logs in, the server generates a token (like a JWT - JSON Web Token) and sends it back to the client. The client then includes this token in the Authorization header of every subsequent request.

Our GraphQL server, however, doesn't directly interact with HTTP headers. This is where the context object comes into play. The context is an object that gets passed to every resolver in a GraphQL operation. We can use it to share information, like the currently authenticated user, across all our resolvers.

Here's a simplified look at how it works:

  1. The client sends a request with an Authorization header.
  2. Before the GraphQL execution starts, our server-side code (often in a middleware) reads the token from the header.
  3. It verifies the token to identify the user.
  4. If the token is valid, the user's information is added to the context object.
  5. Now, every resolver can access context.user to see who is making the request.

Example (using Apollo Server):

javascript
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import jwt from 'jsonwebtoken';

// Assume you have your typeDefs and resolvers defined elsewhere

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

const { url } = await startStandaloneServer(server, {
  context: async ({ req }) => {
    // Get the user token from the headers.
    const token = req.headers.authorization || '';

    // Try to retrieve a user with the token
    try {
      const user = jwt.verify(token, 'YOUR_SECRET_KEY');
      // Add the user to the context
      return { user };
    } catch (e) {
      // If the token is invalid, the user is not authenticated
      return {};
    }
  },
  listen: { port: 4000 },
});

console.log(`πŸš€  Server ready at: ${url}`);

Now, in any of your resolvers, you can access the context to get the authenticated user:

javascript
const resolvers = {
  Query: {
    me: (parent, args, context, info) => {
      // If there's no user on the context, they're not logged in!
      if (!context.user) {
        throw new Error('You must be logged in to do that!');
      }
      return context.user;
    },
  },
};

Fun Fact: While JWTs are super popular for tokens, you can also use session-based authentication with cookies. The principle remains the same: extract the session information and add the user to the context!


2. Authorization: Protecting Queries and Mutations πŸ’‚β€β™‚οΈ

The Problem: Now that we know who the user is, how do we control what they can do? We don't want any regular user to be able to, for example, delete another user's account.

The Solution: Resolver-Level Checks

The simplest and most direct way to implement authorization is to add checks directly within your resolvers. Since our resolvers have access to the authenticated user via the context, we can write logic to determine if they have the necessary permissions.

Example:

Let's imagine we have a deletePost mutation. We only want the author of a post to be able to delete it.

javascript
const resolvers = {
  Mutation: {
    deletePost: async (parent, { postId }, { user, db }) => {
      // 1. Check if the user is even logged in
      if (!user) {
        throw new Error('Authentication required!');
      }

      // 2. Find the post they want to delete
      const post = await db.getPostById(postId);
      if (!post) {
        throw new Error('Post not found!');
      }

      // 3. Check if the logged-in user is the author of the post
      if (post.authorId !== user.id) {
        throw new Error('You are not authorized to delete this post.');
      }

      // 4. If all checks pass, proceed with deleting the post
      await db.deletePost(postId);
      return { success: true };
    },
  },
};

This approach is clear and easy to understand. However, as your application grows, you might find yourself repeating the same authorization logic in multiple resolvers. To keep your code clean, you can extract this logic into reusable helper functions.


3. Field-Level Authorization: Hiding Sensitive Data 🀫

The Problem: What if a user is allowed to see some of an object's data, but not all of it? For instance, you might want a user to see their own email address, but not the email addresses of other users.

The Solution: Field-Level Resolvers and Directives

GraphQL's power lies in its ability to request specific fields. This also means we need to be able to apply authorization at the field level.

One way to do this is by defining a resolver for a specific field.

Example:

Let's say our User type has an email field. We only want to return the email if the user is requesting their own profile or if the user has an 'admin' role.

javascript
const resolvers = {
  User: {
    email: (user, args, context, info) => {
      // If the requesting user is the same as the user being queried,
      // or if the requesting user is an admin, return the email.
      if (context.user && (context.user.id === user.id || context.user.role === 'admin')) {
        return user.email;
      }
      // Otherwise, return null to hide the email.
      return null;
    },
  },
};

This works well, but for more complex authorization rules across many fields, it can become repetitive. A more declarative approach is to use schema directives. Directives allow you to add metadata to your schema, which can then be used by your server to implement cross-cutting concerns like authorization.

Example with Schema Directives:

First, you would define a directive in your schema:

graphql
directive @auth(requires: Role = ADMIN) on FIELD_DEFINITION

enum Role {
  ADMIN
  USER
}

Then, you can apply this directive to specific fields:

graphql
type User {
  id: ID!
  name: String
  email: String @auth(requires: ADMIN)
}

Finally, you would implement the logic for the @auth directive in your server code. Libraries like graphql-tools and graphql-shield can help with this. The implementation would check the user's role from the context and compare it to the requires argument of the directive. If the user doesn't have the required role, the field will be resolved to null or an error will be thrown.


4. Graceful Error Handling for Unauthorized Access 🚫

The Problem: When a user tries to do something they are not allowed to, what should our API return? A generic "Internal Server Error" can be confusing and unhelpful.

The Solution: Clear and Consistent Error Messages

It's crucial to provide clear and informative error messages when authorization fails. Instead of letting an error bubble up and cause a server crash, we should catch it and return a proper GraphQL error.

Unlike traditional REST APIs that rely heavily on HTTP status codes (like 401 for Unauthorized and 403 for Forbidden), GraphQL APIs typically return a 200 OK status code even when there are errors. The errors are then included in a separate errors array in the JSON response.

Example of a good error response:

json
{
  "data": {
    "deletePost": null
  },
  "errors": [
    {
      "message": "You are not authorized to delete this post.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "deletePost"
      ],
      "extensions": {
        "code": "FORBIDDEN"
      }
    }
  ]
}

By providing a descriptive message and a custom code, you make it much easier for the client-side application to handle the error appropriately, perhaps by displaying a user-friendly message or redirecting the user. Libraries like graphql-shield can help standardize these error responses.

A word of caution: Be careful not to leak sensitive information in your error messages. For example, instead of saying "User with ID 123 does not have the 'admin' role", a more secure message would be "You do not have permission to perform this action."

By implementing these authentication and authorization strategies, you can build a secure and robust GraphQL API that protects your data and provides a great developer experience. Happy coding! πŸš€


πŸ“š Extra Reading:

Challenge

You are tasked with securing a GraphQL API for a blogging platform. Your specific goal is to implement the authorization logic within the deletePost mutation resolver.

Schema Definitions:

graphql
type Post {
  id: ID!
  title: String!
  authorId: ID!
}

type User {
  id: ID!
  username: String!
}

type Mutation {
  deletePost(postId: ID!): String
}

Requirements:

  1. Complete the deletePost resolver function. This function receives args (containing postId) and context (containing the authenticated user object) as arguments.
  2. Find the post from the posts data array using the postId. If no post is found, throw an error with the message "Post not found."
  3. The core of your task is to enforce an authorization rule: a user can only delete a post if their id matches the post's authorId.
  4. If the user is not the author, you must throw a GraphQL-compliant error. This error must have a message property set to "You are not authorized to delete this post." and an extensions property containing an object { "code": "FORBIDDEN" }.
  5. If the user is authorized, return the success string "Post successfully deleted.".

Expected result

The final code should feature a fully implemented deletePost resolver function. The function's logic must perform the following steps in order:

  1. It correctly extracts postId from the args object and user from the context object.
  2. It uses the postId to search the posts array and find the corresponding post object.
  3. It includes a check that throws an error with the message "Post not found." if the search yields no result.
  4. It strictly compares the post.authorId against the context.user.id.
  5. If the IDs do not match, it instantiates and throws a GraphQLError with the message "You are not authorized to delete this post." and an extensions object { "code": "FORBIDDEN" }.
  6. If the authorization check passes, it returns the string "Post successfully deleted.". The solution does not need to modify the posts array.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.