DEV Community

Cover image for Authentication and authorization — Fastify with TypeScript (part 12/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Authentication and authorization — Fastify with TypeScript (part 12/18)

Authentication and authorization

Twelfth chapter of the "Fastify with TypeScript" series. Let's put together plugins, hooks, decorators and error handling to build a complete JWT authentication system with role-based access control. By the end, users will have hashed passwords, a login route will hand out tokens, and two of our routes will require one.


npm install @fastify/jwt argon2
Enter fullscreen mode Exit fullscreen mode

@fastify/jwt signs and verifies JSON Web Tokens. argon2 hashes passwords with Argon2id. It is a binding to the reference implementation of the algorithm, written in C, and it does the work off the main thread, so hashing doesn't block the event loop. The package ships prebuilt binaries for Linux (including Alpine), Apple Silicon Macs and Windows, so on those systems there is nothing to compile; elsewhere npm install builds it and needs a C++ compiler.

Storing a password hash

Never store a password. Store a hash of it: a value that can verify the password but can't be turned back into it. Our stored users need one more field, so update src/plugins/store.ts:

// src/plugins/store.ts
import fp from 'fastify-plugin';
import type { UserResponseType } from '../users/users.schema.ts';

// What we keep for each user: the public fields plus the password hash
export interface StoredUser extends UserResponseType {
  password_hash: string;
}

interface Store {
  users: StoredUser[];
}

declare module 'fastify' {
  interface FastifyInstance {
    store: Store;
  }
}

// Temporary in-memory storage shared by every module: PostgreSQL replaces it in chapter 13
export default fp(async function storePlugin(fastify) {
  fastify.decorate('store', { users: [] });
}, { name: 'store' });
Enter fullscreen mode Exit fullscreen mode

StoredUser is everything in the public UserResponse plus password_hash. That hash must never appear in a response, and it won't: the response schemas from chapter 7 don't declare it, so Fastify leaves it out.

The auth plugin

The checks we need (is there a valid token? does this user have the right role?) are the same for every route, so they are written once and shared as decorators. Create src/plugins/auth.ts:

// src/plugins/auth.ts
import fp from 'fastify-plugin';
import fastifyJwt from '@fastify/jwt';
import createError from '@fastify/error';
import type { FastifyReply, FastifyRequest } from 'fastify';
import type { Role } from '../users/users.schema.ts';

export interface JwtPayload {
  id: string;
  email: string;
  role: Role;
}

export const Unauthorized = createError('UNAUTHORIZED', 'Missing or invalid token', 401);
export const Forbidden = createError('FORBIDDEN', 'You are not allowed to do this', 403);

declare module '@fastify/jwt' {
  interface FastifyJWT {
    payload: JwtPayload; // what you pass to app.jwt.sign()
    user: JwtPayload;    // what request.user looks like after jwtVerify()
  }
}

declare module 'fastify' {
  interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
    authorize: (...roles: Role[]) => (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
  }
}

export default fp(async function authPlugin(fastify) {
  await fastify.register(fastifyJwt, {
    secret: fastify.config.JWT_SECRET,
    sign: { expiresIn: '1h' },
  });

  fastify.decorate('authenticate', async function (request) {
    try {
      await request.jwtVerify();
    } catch {
      throw new Unauthorized(); // handled by the central error handler
    }
  });

  fastify.decorate('authorize', function (...allowedRoles) {
    return async function (request, reply) {
      await fastify.authenticate(request, reply);
      if (!allowedRoles.includes(request.user.role)) throw new Forbidden();
    };
  });
}, { name: 'auth' });
Enter fullscreen mode Exit fullscreen mode

What's going on:

  • fastify.config.JWT_SECRET is a string (not string | undefined like process.env.JWT_SECRET), thanks to the configuration from chapter 4. Tokens expire after one hour.
  • @fastify/jwt decorates request.user itself. We type it by augmenting FastifyJWT, not FastifyRequest: payload types what goes into sign(), user what comes out of jwtVerify().
  • authenticate and authorize are our own decorators, declared on FastifyInstance as in the previous chapter. authorize('admin') returns a hook, so each route can say which roles it accepts.
  • Both throw typed errors. An error thrown from a hook stops the request, and the error handler from chapter 10 turns it into a response, so a 401 or a 403 has exactly the same shape as every other error of the API.
  • Role comes from users.schema.ts, so the list of roles is written in one place only.

Register it in src/app.ts. Add the import:

import auth from './plugins/auth.ts';
Enter fullscreen mode Exit fullscreen mode

and register it after the store plugin:

  app.register(auth);
Enter fullscreen mode Exit fullscreen mode

Hashing on sign-up and protecting routes

Now the users module. POST / must hash the password, and the two GET routes must ask for a token. This is the complete src/users/users.route.ts:

// src/users/users.route.ts
import { Type } from 'typebox';
import { hash } from 'argon2';
import createError from '@fastify/error';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import {
  CreateUserBody,
  ListUsersQuery,
  UserParams,
  UserResponse,
} from './users.schema.ts';
import type { StoredUser } from '../plugins/store.ts';

const UserNotFound = createError('USER_NOT_FOUND', 'User %s not found', 404);
const EmailTaken = createError('EMAIL_TAKEN', 'Email %s is already registered', 409);

const userRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
  const { users } = fastify.store;

  fastify.get('/', {
    schema: {
      tags: ['users'],
      security: [{ bearerAuth: [] }],
      querystring: ListUsersQuery,
      response: { 200: Type.Array(UserResponse) },
    },
    onRequest: [fastify.authorize('admin')],
  }, async (request) => {
    const { limit = 10 } = request.query; // a number: validated and converted by the schema
    return users.slice(0, limit);
  });

  fastify.get('/:id', {
    schema: {
      tags: ['users'],
      security: [{ bearerAuth: [] }],
      params: UserParams,
      response: { 200: UserResponse },
    },
    onRequest: [fastify.authenticate],
  }, async (request) => {
    const user = users.find((u) => u.id === request.params.id);
    if (!user) throw new UserNotFound(request.params.id);
    return user;
  });

  fastify.post('/', {
    schema: {
      tags: ['users'],
      body: CreateUserBody,
      response: { 201: UserResponse },
    },
  }, async (request, reply) => {
    const { name, email, password } = request.body;
    if (users.some((u) => u.email === email)) throw new EmailTaken(email);

    // Never store the password itself, only a hash of it
    const password_hash = await hash(password, { memoryCost: 65536, timeCost: 3, parallelism: 4 });
    const user: StoredUser = { id: crypto.randomUUID(), name, email, role: 'user', password_hash };
    users.push(user);

    reply.code(201);
    reply.header('Location', `/api/v1/users/${user.id}`);
    return user;
  });
};

export default userRoutes;
Enter fullscreen mode Exit fullscreen mode

Compared with the previous chapter:

  • POST / hashes the password and stores a StoredUser. It still returns user, hash included, and relies on the response schema to strip it.
  • GET /:id has onRequest: [fastify.authenticate]: any logged-in user can read a user.
  • GET / has onRequest: [fastify.authorize('admin')]: only admins can list everyone.
  • security: [{ bearerAuth: [] }] is for the OpenAPI document: it tells whoever reads the contract, and every generated client, that the route needs a bearer token. It documents the requirement; the onRequest hook is what enforces it.

The name bearerAuth has to be declared once. In src/plugins/openapi.ts, add components to the options:

// src/plugins/openapi.ts
import fp from 'fastify-plugin';
import swagger from '@fastify/swagger';

export default fp(async function openapiPlugin(fastify) {
  // The OpenAPI document is generated from the route schemas
  await fastify.register(swagger, {
    openapi: {
      openapi: '3.1.0',
      info: { title: 'My Fastify App', version: '1.0.0' },
      components: {
        securitySchemes: {
          bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
        },
      },
    },
  });

  fastify.get('/openapi.json', { schema: { hide: true } }, async () => fastify.swagger());
}, { name: 'openapi' });
Enter fullscreen mode Exit fullscreen mode

Login

The auth module follows the same layout as users. Create src/auth/auth.schema.ts:

// src/auth/auth.schema.ts
import { Type, type Static } from 'typebox';

export const LoginBody = Type.Object({
  email: Type.String({ format: 'email' }),
  password: Type.String(),
});

export const LoginResponse = Type.Object({
  token: Type.String(),
});

export type LoginBodyType = Static<typeof LoginBody>;
Enter fullscreen mode Exit fullscreen mode

and src/auth/auth.route.ts:

// src/auth/auth.route.ts
import { verify } from 'argon2';
import createError from '@fastify/error';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { LoginBody, LoginResponse } from './auth.schema.ts';

const InvalidCredentials = createError('INVALID_CREDENTIALS', 'Invalid email or password', 401);

// Argon2id hash of a random string nobody knows, with the same parameters as real hashes.
const DUMMY_HASH = '$argon2id$v=19$m=65536,t=3,p=4$QILZ4fJyOMMpkXQnKPjP9w$yM7sx7qU2rUnHRyaAnmTBMwzW9+BRCXbJ1NhlPG+2+Y';

const authRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
  const { users } = fastify.store;

  fastify.post('/login', {
    schema: { tags: ['auth'], body: LoginBody, response: { 200: LoginResponse } },
  }, async (request) => {
    const { email, password } = request.body;
    const user = users.find((u) => u.email === email);
    const valid = await verify(user?.password_hash ?? DUMMY_HASH, password);
    if (!user || !valid) throw new InvalidCredentials();

    const token = fastify.jwt.sign({ id: user.id, email: user.email, role: user.role });
    return { token };
  });

  fastify.get('/me', {
    schema: { tags: ['auth'], security: [{ bearerAuth: [] }] },
    onRequest: [fastify.authenticate],
  }, async (request) => {
    return { user: request.user }; // typed as JwtPayload
  });
};

export default authRoutes;
Enter fullscreen mode Exit fullscreen mode

The module reads the users from fastify.store, the decorator we created in the previous chapter for exactly this purpose.

Register it in src/app.ts, with its import, just above the users routes:

import authRoutes from './auth/auth.route.ts';
Enter fullscreen mode Exit fullscreen mode
  app.register(authRoutes, { prefix: '/auth' });
Enter fullscreen mode Exit fullscreen mode

Two security details in the login handler:

  • "Unknown email" and "wrong password" get the same 401. Don't tell an attacker which half they got right.
  • The response time must not tell them either. Verifying an Argon2 hash takes tens of milliseconds, so an answer that comes back instantly would reveal that the email doesn't exist. That's what DUMMY_HASH is for: when there is no user, we verify the password against a throwaway hash and do the same amount of work. Generate your own once and paste it in:
node -e "import('argon2').then(async (a) => console.log(await a.hash(require('node:crypto').randomBytes(32).toString('hex'), { memoryCost: 65536, timeCost: 3, parallelism: 4 })))"
Enter fullscreen mode Exit fullscreen mode

Try it

Create a user (the server restarted, so the store is empty):

curl -X POST localhost:3000/api/v1/users \
  -H 'content-type: application/json' \
  -d '{"name":"Grace","email":"grace@example.com","password":"correct-horse"}'
# {"id":"f304e062-2431-44b4-99d2-5adc0bad94f7","name":"Grace","email":"grace@example.com","role":"user"}
Enter fullscreen mode Exit fullscreen mode

No password_hash in the response, as promised. Log in:

curl -X POST localhost:3000/auth/login \
  -H 'content-type: application/json' \
  -d '{"email":"grace@example.com","password":"correct-horse"}'
# {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}
Enter fullscreen mode Exit fullscreen mode

Copy the token into a shell variable (TOKEN=eyJ...) and use it:

curl localhost:3000/auth/me -H "authorization: Bearer $TOKEN"
# {"user":{"id":"f304e062-2431-44b4-99d2-5adc0bad94f7","email":"grace@example.com","role":"user","iat":1795538242,"exp":1795541842}}

curl localhost:3000/api/v1/users/f304e062-2431-44b4-99d2-5adc0bad94f7 -H "authorization: Bearer $TOKEN"
# {"id":"f304e062-2431-44b4-99d2-5adc0bad94f7","name":"Grace","email":"grace@example.com","role":"user"}
Enter fullscreen mode Exit fullscreen mode

And the failures:

curl localhost:3000/auth/me
# {"statusCode":401,"error":"UNAUTHORIZED","message":"Missing or invalid token"}

curl localhost:3000/api/v1/users -H "authorization: Bearer $TOKEN"
# {"statusCode":403,"error":"FORBIDDEN","message":"You are not allowed to do this"}

curl -X POST localhost:3000/auth/login \
  -H 'content-type: application/json' \
  -d '{"email":"nobody@example.com","password":"wrong-password"}'
# {"statusCode":401,"error":"INVALID_CREDENTIALS","message":"Invalid email or password"}
Enter fullscreen mode Exit fullscreen mode

The 403 is correct: Grace is authenticated but she is a plain user, and the list is for admins. There is no way to make her an admin while the users live in memory. We'll do it in the next chapter, with one line of SQL.

The token is not encrypted, only signed. Its middle part is base64-encoded JSON that anyone can read ({"id":"...","email":"grace@example.com","role":"user",...}), so never put a secret in a JWT payload. What the signature guarantees is that nobody can change it, for example turning user into admin, without the server noticing.

For authentication endpoints, always apply a stricter rate limit than the rest of the API, to protect them from brute-force attacks. We'll add it in chapter 14.


⬅️ Previous chapter: Decorators · ➡️ Next chapter: Database

This article is part of the "Fastify with TypeScript" series — chapter 12 of 18.

Top comments (0)