">
 

How to Implement Role-Based Access Control in a Node.js REST API with JWT

Iniciado por joomlamz, Ontem às 22:15

Respostas: 0   |   Visualizações: 5

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.


                     How to Implement Role-Based Access Control in a Node.js REST API with JWT
               




Tópico:
                     How to Implement Role-Based Access Control in a Node.js REST API with JWT
               
Categoria: Tutoriais | FreeCodeCamp Premium
Idioma Principal: Português (Conteúdo de Tecnologia)

Conteúdo do Tutorial / Guia Passo a Passo:
-------------------------------------------------------------------------
The first time I built an API without thinking about roles, I gave every logged-in user the same access. It worked fine until a regular user accidentally hit a delete endpoint and wiped test data. That was the day I actually sat down and learned RBAC properly.

Role-Based Access Control sounds fancy, but the idea is simple: what you can do depends on who you are, not just that you're logged in. An admin deletes users. An editor creates posts. A regular user just reads. Same app, completely different experience depending on who's asking.

That's what we're building here. A REST API with three roles: JWT to carry those roles on every request, and a pair of middleware functions that check permissions before your route handlers even run. There's no database hit per request, and no if/else soup in your business logic.

By the end, you'll have three working roles (
admin,
editor,
user) each locked to their own endpoints. More importantly, the pattern is transferable: once it clicks, you'll wire it into your next project without needing a tutorial.

Full source code on GitHub: github.com/ziaongit/nodejs-rbac-jwt-api

Table of Contents

• What You'll Learn

• Prerequisites

• What We'll Build

• Project Setup

• Setting Up the In-Memory Data Store

• Building the Auth Routes

• Building the RBAC Middleware

• Building the Protected Routes

• Putting It All Together

• Testing the API

• Key Takeaways

• Conclusion

What You'll Learn

• What RBAC is and how it differs from basic authentication

• How to embed roles in JWT payloads

• How to write reusable Express middleware for token verification and role checking

• How to protect API routes based on user roles

Prerequisites

• Node.js (v18+) installed

• Basic knowledge of Express.js

• Familiarity with how JWTs work (we'll cover the relevant parts)

• npm installed

What We'll Build

We'll build a REST API for a simple content management system with three user roles:

Role
Permissions

user
Read content

editor
Read + create content

admin
Full access — read, create, delete content, manage users

The API will expose these endpoints:

Method
Endpoint
Access

POST
/api/auth/register
Public

POST
/api/auth/login
Public

GET
/api/content
user, editor, admin

POST
/api/content
editor, admin

DELETE
/api/content/:id
admin only

GET
/api/admin/users
admin only

Project Setup

Create a new folder and initialize the project:

mkdir nodejs-rbac-jwt-api
cd nodejs-rbac-jwt-api
npm init -y

Install the dependencies:

npm install express jsonwebtoken bcryptjs dotenv
npm install --save-dev nodemon

Here's what each package does:

• express: web framework for building the API

• jsonwebtoken: creates and verifies JWTs

• bcryptjs: securely hashes passwords

• dotenv: reads your
.envfile so you're not hardcoding secrets in your source code

Update
package.jsonto add start scripts:

"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
}

Create the project structure:

nodejs-rbac-jwt-api/
├── src/
│   ├── middleware/
│   │   └── auth.js
│   ├── routes/
│   │   ├── auth.js
│   │   ├── content.js
│   │   └── admin.js
│   ├── data/
│   │   └── users.js
│   └── app.js
├── .env
├── .env.example
└── package.json

... [O tutorial continua no link abaixo] ...


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: