GraphQL Part 4 - Let’s build the Authentication layer

A hand turns a glowing key in the lock of a chained vault door, beside a sealed scroll labelled JSON Web Token

In Part 3 we moved our Hammer collection into MongoDB, so our changes finally survive a restart. But there is a problem. Anyone who can reach the server can add films, mark them as watched, or delete the lot. Our archive has no lock on the door.

In this post we’ll build the authentication layer. To do this right in 2026, we’ll use JWTs (JSON Web Tokens). This allows your server to stay "stateless": it doesn't have to remember every logged-in user, it just has to trust the "digital seal" (the token) they carry.

We need to add four things:

  • A User Model: To store credentials (with hashed passwords, never store plain text!).
  • Auth Mutations: signup and login operations that return a token.
  • The Context Hook: A way for Apollo to check for a token before every request.
  • Guards: Checks in our resolvers so only logged-in users can change the archive, and only an admin can delete from it.

We’ll build on the code from Part 3, adding two new packages: jsonwebtoken creates and checks the tokens, and bcryptjs hashes passwords. If you’re following along in your Part 3 folder, install them now:

bash
cd lab/graphql-tutorial-3
npm install jsonwebtoken bcryptjs

If you’d rather jump straight to the finished code, it’s in the graphql-tutorial-4 folder of the lab repository:

bash
git clone https://github.com/jmwollny/lab.git
cd lab/graphql-tutorial-4
npm install

The User Model

First, we need a way to store users. Create models/User.js next to Film.js:

javascript
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  role: { type: String, enum: ['HUNTER', 'ADMIN'], default: 'HUNTER' }
});

// Hash the password before it is saved, so it is never stored as plain text
userSchema.pre('save', async function () {
  if (!this.isModified('password')) return;
  this.password = await bcrypt.hash(this.password, 10);
});

module.exports = mongoose.model('User', userSchema);

Every new user is a HUNTER. The ADMIN role is for the trusted few, and we’ll use it later to decide who is allowed to destroy films.

The pre('save') hook runs just before a user is written to the database and swaps the password for a bcrypt hash. The 10 is the cost factor: how much work it takes to compute the hash. Higher is slower for an attacker trying to guess passwords, but also slower for your server.

Creating and Checking Tokens

Both the login code and the request check need the same secret, so let's keep everything to do with tokens in one place. Create auth.js:

javascript
const jwt = require('jsonwebtoken');

// In production, set JWT_SECRET as an environment variable. The fallback is for local development only.
const SECRET = process.env.JWT_SECRET || 'VAN_HELSING_SECRET';

// Seal the user's id and role into a token that expires after 7 days
const createToken = (user) =>
  jwt.sign({ userId: user.id, role: user.role }, SECRET, { expiresIn: '7d' });

// Read the user from an "Authorization: Bearer <token>" header. Returns null if there is no valid token.
const getUser = (header = '') => {
  const token = header.replace('Bearer ', '');
  if (!token) return null;
  try {
    return jwt.verify(token, SECRET);
  } catch {
    return null; // expired, or tampered with
  }
};

module.exports = { createToken, getUser };

jwt.sign packs the user's id and role into the token and signs it with the secret. jwt.verify checks that signature. If anyone edits the token (say, changing their role to ADMIN) or it has expired, verification fails and we treat the request as anonymous.

Keep the secret secret. Anyone who knows it can forge a token for any user.

Update the Type Definitions

Now for the schema. In index.js, add a User type, an AuthPayload type for what signup and login return, and the two new mutations:

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

type AuthPayload {
  token: String!
  user: User!
}

type Mutation {
  # ... existing mutations ...

  # Create an account and get a token
  signup(username: String!, password: String!): AuthPayload

  # Swap a username and password for a token
  login(username: String!, password: String!): AuthPayload
}

Notice that the User type has no password field. The hash lives in MongoDB, but because it isn't in the schema, GraphQL can never send it to a client.

Implement the Resolvers

This is where the heavy lifting happens: checking passwords and signing tokens. At the top of index.js, pull in Apollo's error classes along with the new modules:

javascript
const { ApolloServer, gql, AuthenticationError, ForbiddenError, UserInputError } = require('apollo-server');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const FilmModel = require('./models/Film');
const User = require('./models/User');
const { createToken, getUser } = require('./auth');

Then add signup and login to the Mutation resolvers:

javascript
Mutation: {
  // SIGNUP: create a user and return a token
  signup: async (parent, { username, password }) => {
    if (await User.exists({ username })) {
      throw new UserInputError('That username is already taken');
    }
    const user = await User.create({ username, password });
    return { token: createToken(user), user };
  },

  // LOGIN: check the credentials and return a token
  login: async (parent, { username, password }) => {
    const user = await User.findOne({ username });
    const valid = user && (await bcrypt.compare(password, user.password));
    if (!valid) {
      throw new AuthenticationError('Invalid username or password');
    }
    return { token: createToken(user), user };
  },

  // ... your existing addFilm, updateWatched and deleteFilm ...
}

bcrypt.compare hashes the password the user typed and checks it against the stored hash. We never need to turn the hash back into the password (and we can't).

Login gives the same error whether the username doesn't exist or the password is wrong. That's deliberate: a different message for each would tell an attacker which usernames are real.

The Context Hook

Next, we change how the server starts. We want to peek at the Authorization header on every request:

javascript
const server = new ApolloServer({
  typeDefs,
  resolvers,
  // Runs before every request: whatever it returns is the third argument of every resolver
  context: ({ req }) => ({ user: getUser(req.headers.authorization) }),
});

With a valid token, context.user holds the token's contents (userId and role). Without one, it's null. Queries don't look at it, so anyone can still browse the archive.

Protecting the Resolvers

Now let's make sure only a logged-in user can change the archive. Add two small guards above the resolvers:

javascript
const requireUser = (context) => {
  if (!context.user) {
    throw new AuthenticationError('You must be a registered Hunter to modify the archive!');
  }
  return context.user;
};

const requireAdmin = (context) => {
  if (requireUser(context).role !== 'ADMIN') {
    throw new ForbiddenError('Only an Admin can destroy a film');
  }
};

Then call them at the start of each mutation. Resolvers receive the context as their third argument, so add context to each one:

javascript
addFilm: async (parent, { input }, context) => {
  requireUser(context);
  const newFilm = new FilmModel(input);
  return await newFilm.save();
},

updateWatched: async (parent, { id, watched }, context) => {
  requireUser(context);
  // ... the rest is unchanged from Part 3
},

deleteFilm: async (parent, { id }, context) => {
  requireAdmin(context);
  // ... the rest is unchanged from Part 3
},

Any registered Hunter can add films and track what they've watched, but only an Admin can destroy a film.

The two error classes do more than set a message. Apollo adds a code to the error (UNAUTHENTICATED or FORBIDDEN), so a frontend can tell "please log in" apart from "you're not allowed to do that" without matching on the text.

Testing the Flow in the Sandbox

Restart your server with node index.js and open http://localhost:4000/. Then follow this sequence.

1. Try a protected mutation without a token. It should be refused:

graphql
mutation {
  addFilm(input: { title: "The Abominable Snowman", year: 1957, watched: false }) {
    id
    title
  }
}
json
{
  "errors": [
    {
      "message": "You must be a registered Hunter to modify the archive!",
      "path": ["addFilm"],
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ],
  "data": {
    "addFilm": null
  }
}

2. Sign up:

graphql
mutation {
  signup(username: "VanHelsing", password: "garlic-and-stakes") {
    token
    user {
      username
      role
    }
  }
}

3. Copy the token. You’ll get a long string back, starting eyJ.

4. Set the Authorization header. In the Apollo Sandbox, open the Headers tab at the bottom and add:

  • Key: Authorization
  • Value: Bearer YOUR_TOKEN_HERE

5. Run the addFilm mutation again. This time the context function verifies the token and lets you through. Marking a film as watched with updateWatched works too.

6. Try to delete the film. You'll get a FORBIDDEN error, because VanHelsing is only a HUNTER. To promote him, open the Mongo shell:

bash
mongosh hammer_films --eval 'db.users.updateOne({ username: "VanHelsing" }, { $set: { role: "ADMIN" } })'

Run deleteFilm again and it is still forbidden. The role is sealed inside the token, and that token was issued when VanHelsing was a mere Hunter. Run the login mutation, put the new token in the header, and the delete goes through.

That last step shows the trade-off of tokens. The server trusts what the token says until it expires, so changes to a user's role (or a ban) only take effect at their next login. That's why we gave our tokens a 7-day expiry rather than letting them live forever.

Why Stateless?

By using this method, your server doesn't have a "session" it needs to keep track of in memory. The token itself contains the user's ID and role. If your server crashes and restarts, the user stays logged in because the token is still valid. And if you run several copies of the server, any of them can check the token, because all they need is the secret.

Conclusion

We began this journey with nothing but a local array and a list of Hammer films. Over the course of this series, we’ve transformed that humble start into a GraphQL/MongoDB ecosystem.

What We’ve Built

  • The Blueprint (Part 1): We defined our schema and learned how to query data with the precision of a surgeon.
  • The Mutation (Part 2): We moved beyond "Read-Only" and gave our API the power to create, update, and delete records.
  • The Immortal Vault (Part 3): We integrated MongoDB, ensuring our data survives a server restart and scales as our collection grows.
  • The Gatekeeper (Part 4): We secured the archive with JWT Authentication and bcrypt hashing, with roles deciding who can do what.

What’s Next for You?

Suggestions to try.

  1. Deployment: Take your API out of localhost and host it on a platform like Railway or Render. Remember to set JWT_SECRET there rather than relying on the fallback.
  2. Frontend Integration: Build a React or Next.js dashboard to visualize your "Watched" list, with a login form that stores the token and sends it with each request.
  3. Per-user Watch Lists: At the moment, "watched" is shared by everyone. Try storing it against each user instead, so every Hunter keeps their own list.
  4. Advanced Filtering: Use MongoDB's aggregation pipelines to find the most prolific directors or actors in your archive.

Happy coding!

Comments