Role-Based Authorization

Introduction: Why Role-Based Authorization?

Welcome back! In the last lesson, you learned how to protect your API routes so that only authenticated users with a valid JWT can access them. That’s a great start, but in most real-world applications, not all users should have the same permissions. For example, you might want only administrators to be able to delete books or update user information, while regular users can only view data.

In the previous unit we only had JwtAuthGuard: any authenticated user could perform mutations (create/update/delete). That’s intentionally incomplete. In this unit we’ll require roles for sensitive actions. To make this concrete now, we’ll use an admin role (you already have a seeded admin user). In the SPA playground provided with the course you can try both a normal user and an admin; later, in the frontend path, you’ll build your own React UI.

This is where role-based authorization comes in. With role-based authorization, you can control what actions different types of users can perform in your API. In this lesson, you’ll learn how to implement this in your NestJS project so you can restrict certain endpoints to users with specific roles, like admin or user.

Quick Recap: Our API Structure

Before we dive in, let’s quickly remind ourselves of the current setup. You already have:

  • Registration (bcrypt hashes stored).
  • JWT Login (token with sub, role, iat, exp).
  • JwtAuthGuard (only checks if the token is valid → user is logged in).

Here’s a simplified code block to show where we are, focusing on how user roles fit in:

// Example: Protecting a route with JwtAuthGuard
@Patch(':id')
@UseGuards(JwtAuthGuard)
update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() updateBookDto: UpdateBookDto,
) {
    const book = this.booksService.update(id, updateBookDto);
    return { success: true, data: book };
  }

What’s wrong

  • Any logged-in user can call write endpoints (e.g., create a book). That violates least-privilege.

What we’ll add

  • @Roles() decorator to declare required roles on a route.
  • RolesGuard to enforce those requirements after JwtAuthGuard authenticates the user.
  • BooksController write routes become admin-only (read routes remain public or authenticated as you decide).

Creating a Roles Decorator

In NestJS, a decorator is a special function you can use to add extra behavior to classes or methods. We’ll create a custom @Roles() decorator to mark which endpoints require certain roles.

Here’s how you can define it:

// src/common/decorators/roles.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const ROLES_KEY = 'roles';
export type Role = 'user' | 'admin';

export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

Explanation:

  • SetMetadata is a NestJS helper that attaches custom metadata to a route handler or controller.
  • ROLES_KEY is the key we’ll use to store the roles.
  • Role is a TypeScript type for allowed roles.
  • Roles(...roles) is the decorator you’ll use on your endpoints, like @Roles('admin').

What is metadata here?

In Nest, metadata is just key–value data attached to a class or handler at design time. Decorators like @Get() and @Post() also attach metadata. Nest provides the Reflector to read that metadata later (inside guards, interceptors, etc.).

Why SetMetadata?

SetMetadata(ROLES_KEY, roles) writes roles: [...] onto the route handler. The guard will read this value and decide access. This avoids hard-coding roles inside the guard; routes declare their own policy, the guard enforces it.

Example usage in the controller:

// Admin-only write; keep reads open or auth-only:
@Controller('books')
export class BooksController {
    constructor(private readonly booksService: BooksService) {}
    
    @Post()
    @UseGuards(AuthGuard('jwt'), RolesGuard)
    @Roles('admin')
    // Create a new book entry (admin only)
    create(@Body() createBookDto: CreateBookDto) {
        const book = this.booksService.create(createBookDto);
        return { success: true, data: book };
    }
    
    @Get()
    // Retrieve all books. No guards required here
    findAll() {
        const books = this.booksService.findAll();
        return { success: true, data: books };
    }
    
    //...rest of the methods
 }
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