Role-Based Authorization (RBAC) in Express.js

Learn Role-Based Authorization (RBAC) in Express.js using JWT middleware. Restrict event creation to organizer accounts and protect APIs from
Express.js REST API Development Tutorial

Role-Based Authorization (RBAC) in Express.js

Role-Based Authorization (RBAC) হলো একটি security mechanism, যার মাধ্যমে application-এর user-এর assigned role অনুযায়ী নির্দিষ্ট resources এবং features access করার permission দেওয়া হয়। Express.js application-এ RBAC ব্যবহার করে আমরা সহজেই নির্ধারণ করতে পারি কোন user কোন API endpoint access করতে পারবে।

ধরুন, আপনি একটি Event Management Application তৈরি করছেন। এখানে দুই ধরনের user রয়েছে:

  • Organizer: Event create, update এবং manage করতে পারবে।
  • Attendee: Event দেখতে এবং event-এ register করতে পারবে, কিন্তু নতুন event create করতে পারবে না।

এই tutorial-এ আমরা Express.js middleware ব্যবহার করে এমন একটি Role-Based Authorization system তৈরি করব, যেখানে শুধুমাত্র organizer account থেকে Event Creation API ব্যবহার করা যাবে।

1. What is Role-Based Access Control (RBAC)?

RBAC-এর পূর্ণরূপ হলো Role-Based Access Control। এটি এমন একটি authorization system, যেখানে user-এর individual identity-এর পরিবর্তে তার assigned role অনুযায়ী permission নির্ধারণ করা হয়।

উদাহরণস্বরূপ, একটি application-এ নিচের role থাকতে পারে:

Role Permission Access
Admin Manage users, events and settings Full Access
Organizer Create and manage own events Event Management
Attendee View and register for events Limited Access

Authentication vs Authorization

Authentication এবং Authorization দুটি আলাদা security concept।

  • Authentication: User কে, সেটি verify করে। যেমন: Login এবং JWT verification.
  • Authorization: Authenticated user কী করতে পারবে, সেটি নির্ধারণ করে। যেমন: Organizer event create করতে পারবে কি না।

Important!
JWT token valid হলেই user সব API access করতে পারবে না। JWT middleware user-এর identity verify করবে, আর RBAC middleware তার permission check করবে।

2. How RBAC Works in Express.js

আমাদের application-এ RBAC system নিচের flow অনুসরণ করবে:

  1. User email এবং password দিয়ে login করবে।
  2. Server credentials verify করবে।
  3. Server JWT access token generate করবে, যেখানে user ID এবং role থাকবে।
  4. User protected API request পাঠাবে।
  5. Authentication middleware JWT verify করবে।
  6. Authorization middleware user-এর role check করবে।
  7. Role যদি organizer হয়, তাহলে event creation permission পাবে।
  8. Role যদি attendee হয়, তাহলে server 403 Forbidden response দেবে।

RBAC Architecture

Client Request
      |
      v
JWT Authentication Middleware
      |
      v
Verify User Identity
      |
      v
RBAC Authorization Middleware
      |
      v
Check User Role
      |
      +----------------------+
      |                      |
      v                      v
 Organizer                Attendee
      |                      |
      v                      v
Create Event API        403 Forbidden
      |
      v
Event Controller
      |
      v
Database

3. Project Setup

প্রথমে একটি Node.js এবং Express.js project তৈরি করুন। Terminal-এ নিচের commands run করুন:

mkdir event-management-api
cd event-management-api

npm init -y

npm install express jsonwebtoken dotenv bcrypt
npm install -D nodemon

Project Folder Structure

event-management-api/
│
├── src/
│   ├── config/
│   │
│   ├── controllers/
│   │   └── event.controller.js
│   │
│   ├── middleware/
│   │   ├── auth.middleware.js
│   │   └── role.middleware.js
│   │
│   ├── routes/
│   │   └── event.routes.js
│   │
│   ├── app.js
│   └── server.js
│
├── .env
├── .gitignore
└── package.json

4. Configure Environment Variables

Project root directory-তে .env file তৈরি করুন। JWT secret এবং server port এখানে রাখুন।

PORT=5000
JWT_SECRET=your_long_random_secret_key
JWT_EXPIRES_IN=15m

.gitignore file:

node_modules/
.env

Security Note!
Production environment-এ একটি strong, random JWT secret ব্যবহার করবেন। কখনোই .env file GitHub repository-তে push করবেন না।

5. Generate JWT with User Role

RBAC implement করার জন্য JWT payload-এর মধ্যে user ID এবং role রাখতে হবে। User login successful হলে server token generate করবে।

Example JWT payload:

{
  "sub": "user_123",
  "role": "organizer",
  "iat": 1795950000,
  "exp": 1795950900
}

এখানে:

  • sub হলো user-এর unique identifier।
  • role হলো user-এর assigned role।
  • iat হলো token issue হওয়ার timestamp।
  • exp হলো token expiration timestamp।

Example Token Generation

Login controller-এ successful authentication-এর পর নিচের code ব্যবহার করতে পারেন:

const jwt = require("jsonwebtoken");

const generateAccessToken = (user) => {
  return jwt.sign(
    {
      role: user.role
    },
    process.env.JWT_SECRET,
    {
      subject: user.id,
      expiresIn: process.env.JWT_EXPIRES_IN,
      algorithm: "HS256",
      issuer: "event-management-api",
      audience: "event-management-client"
    }
  );
};

module.exports = generateAccessToken;

Login সফল হলে:

const token = generateAccessToken(user);

res.status(200).json({
  success: true,
  message: "Login successful",
  accessToken: token
});

Important: এখানে user.role অবশ্যই trusted database record থেকে আসতে হবে। Client request body থেকে role নিয়ে token তৈরি করবেন না।

6. Create JWT Authentication Middleware

এখন আমাদের প্রথম middleware তৈরি করতে হবে। এর কাজ হলো incoming request থেকে JWT token extract করা এবং token valid কি না verify করা।

File: src/middleware/auth.middleware.js

const jwt = require("jsonwebtoken");

const authenticateUser = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;

    // Check Authorization header
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      return res.status(401).json({
        success: false,
        message: "Access token is required"
      });
    }

    // Extract token
    const token = authHeader.split(" ")[1];

    // Verify JWT
    const decoded = jwt.verify(
      token,
      process.env.JWT_SECRET,
      {
        algorithms: ["HS256"],
        issuer: "event-management-api",
        audience: "event-management-client"
      }
    );

    // Attach authenticated user
    req.user = {
      id: decoded.sub,
      role: decoded.role
    };

    next();

  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({
        success: false,
        message: "Access token has expired"
      });
    }

    return res.status(401).json({
      success: false,
      message: "Invalid access token"
    });
  }
};

module.exports = authenticateUser;

How Does This Middleware Work?

  • req.headers.authorization থেকে Authorization header নেয়।
  • Bearer prefix আছে কি না check করে।
  • jwt.verify() দিয়ে token verify করে।
  • Valid হলে user ID এবং role req.user-এ রাখে।
  • এরপর next() call করে পরবর্তী middleware বা controller-এ পাঠায়।

7. Create Role-Based Authorization Middleware

এখন আমাদের মূল RBAC middleware তৈরি করতে হবে। এই middleware নির্ধারণ করবে কোন role কোন API access করতে পারবে।

File: src/middleware/role.middleware.js

const authorizeRoles = (...allowedRoles) => {
  return (req, res, next) => {

    // Check authenticated user
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: "Authentication required"
      });
    }

    // Check user role
    if (!allowedRoles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: "You do not have permission to perform this action"
      });
    }

    // User has permission
    next();
  };
};

module.exports = authorizeRoles;

Understanding authorizeRoles()

এখানে authorizeRoles() একটি higher-order middleware function। এটি এক বা একাধিক allowed role গ্রহণ করে এবং একটি middleware return করে।

Example:

authorizeRoles("organizer");

authorizeRoles("admin", "organizer");

authorizeRoles("attendee");

প্রথম উদাহরণে শুধুমাত্র organizer access পাবে। দ্বিতীয় উদাহরণে admin এবং organizer উভয়েই access পাবে।

How does allowedRoles.includes() work?

ধরুন, আমরা নিচের middleware ব্যবহার করছি:

authorizeRoles("organizer")

এখন middleware-এর মধ্যে:

allowedRoles.includes(req.user.role)

এই condition check করবে authenticated user-এর role organizer কি না। Match হলে next() call হবে। Match না হলে 403 Forbidden response পাঠানো হবে।

8. Create Event Controller

এখন Event Creation API-এর controller তৈরি করব। এই example-এ event data database-এ save করার পরিবর্তে response-এ return করা হচ্ছে। Real project-এ এখানে Prisma বা অন্য database ORM ব্যবহার করবেন।

File: src/controllers/event.controller.js

const createEvent = async (req, res, next) => {
  try {
    const { title, description, date } = req.body;

    // Validate required fields
    if (!title || !description || !date) {
      return res.status(400).json({
        success: false,
        message: "Title, description and date are required"
      });
    }

    // Example event data
    const event = {
      id: "event_001",
      title,
      description,
      date,
      organizerId: req.user.id
    };

    return res.status(201).json({
      success: true,
      message: "Event created successfully",
      data: event
    });

  } catch (error) {
    next(error);
  }
};

module.exports = {
  createEvent
};

খেয়াল করুন, এখানে organizerId নেওয়া হয়েছে req.user.id থেকে। Client-এর পাঠানো organizer ID trust করা হচ্ছে না। এতে অন্য user-এর পরিচয় ব্যবহার করে event তৈরি করার ঝুঁকি কমে।

9. Protect Event Creation API

এখন Authentication এবং Authorization middleware একসঙ্গে ব্যবহার করব।

File: src/routes/event.routes.js

const express = require("express");

const router = express.Router();

const authenticateUser = require("../middleware/auth.middleware");
const authorizeRoles = require("../middleware/role.middleware");

const {
  createEvent
} = require("../controllers/event.controller");

// Only organizers can create events
router.post(
  "/",
  authenticateUser,
  authorizeRoles("organizer"),
  createEvent
);

module.exports = router;

Understanding Middleware Execution Order

POST /api/events
       |
       v
authenticateUser
       |
       v
authorizeRoles("organizer")
       |
       v
createEvent
       |
       v
201 Created

Middleware-এর order অত্যন্ত গুরুত্বপূর্ণ। প্রথমে authentication হবে, এরপর authorization check হবে এবং সবশেষে controller execute হবে।

Important!
শুধু authorizeRoles("organizer") ব্যবহার করলে হবে না। তার আগে authenticateUser middleware থাকতে হবে, কারণ RBAC middleware-এর জন্য verified req.user প্রয়োজন।

10. Configure Express Application

এখন routes-গুলো Express application-এর সঙ্গে connect করব।

File: src/app.js

const express = require("express");

const eventRoutes = require("./routes/event.routes");

const app = express();

// Parse JSON request body
app.use(express.json());

// Event API routes
app.use("/api/events", eventRoutes);

// Default route
app.get("/", (req, res) => {
  res.json({
    message: "Event Management API is running"
  });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: "Route not found"
  });
});

module.exports = app;

File: src/server.js

require("dotenv").config();

const app = require("./app");

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

11. Test RBAC Using Postman

এখন Postman ব্যবহার করে আমাদের RBAC middleware test করব। প্রথমে server চালু করুন:

node src/server.js

অথবা nodemon configured থাকলে:

npx nodemon src/server.js

Test 1: Organizer Creates an Event

Method: POST

URL: http://localhost:5000/api/events

Headers:

Authorization: Bearer ORGANIZER_ACCESS_TOKEN
Content-Type: application/json

Request Body:

{
  "title": "JavaScript Workshop",
  "description": "Learn JavaScript fundamentals",
  "date": "2026-12-20"
}

Expected Response:

{
  "success": true,
  "message": "Event created successfully",
  "data": {
    "id": "event_001",
    "title": "JavaScript Workshop",
    "description": "Learn JavaScript fundamentals",
    "date": "2026-12-20",
    "organizerId": "user_123"
  }
}
201 Created

Test 2: Attendee Tries to Create an Event

এবার attendee account-এর valid access token ব্যবহার করে একই API request পাঠান।

Authorization Header:

Authorization: Bearer ATTENDEE_ACCESS_TOKEN

Expected Response:

{
  "success": false,
  "message": "You do not have permission to perform this action"
}
403 Forbidden

Test 3: Request Without a Token

এবার Authorization header ছাড়াই request পাঠান।

Expected Response:

{
  "success": false,
  "message": "Access token is required"
}
401 Unauthorized

12. Authentication vs Authorization HTTP Status Codes

RBAC implement করার সময় সঠিক HTTP status code ব্যবহার করা গুরুত্বপূর্ণ।

Status Code Meaning Example
200 OK Request successful
201 Created Event created successfully
400 Bad Request Required fields missing
401 Unauthorized Missing or invalid token
403 Forbidden Attendee tries to create an event
404 Not Found Requested route does not exist

13. Important RBAC Security Best Practices

Production-level application-এ RBAC implement করার সময় নিচের security practices অনুসরণ করা উচিত:

  • Never Trust Client Roles: User request body বা frontend থেকে role নিয়ে permission নির্ধারণ করবেন না। Trusted database record ব্যবহার করুন।
  • Verify JWT Properly: jwt.verify() ব্যবহার করুন। শুধু jwt.decode() দিয়ে authentication করবেন না।
  • Use Short-Lived Access Tokens: Access token-এর expiry time সীমিত রাখুন।
  • Protect Role Changes: Role update করার permission শুধু authorized admin-কে দিন।
  • Validate Database Ownership: Organizer যেন অন্য organizer-এর event update বা delete করতে না পারে, সেটিও check করুন।
  • Use HTTPS: Production-এ secure HTTPS connection ব্যবহার করুন।
  • Apply Least Privilege: User-কে কাজের জন্য প্রয়োজনীয় minimum permission দিন।
  • Audit Sensitive Actions: Event creation, deletion এবং role changes-এর মতো গুরুত্বপূর্ণ action log করুন।

Important: Role-Based Access vs Resource Ownership

শুধু organizer role থাকলেই সব event update বা delete করার permission দেওয়া উচিত নয়। এখানে resource ownership check করতে হবে।

উদাহরণস্বরূপ:

const canUpdateEvent = (req, res, next) => {
  const event = {
    id: "event_001",
    organizerId: "user_123"
  };

  if (event.organizerId !== req.user.id) {
    return res.status(403).json({
      success: false,
      message: "You can only manage your own events"
    });
  }

  next();
};

এটি একটি simplified demonstration। Real application-এ database থেকে event fetch করে ownership verify করতে হবে।

14. Common RBAC Implementation Mistakes

  • Authentication এবং Authorization-কে একই বিষয় মনে করা।
  • JWT verify না করে token decode করে user-কে trust করা।
  • Frontend-এ button hide করলেই API secure হয়েছে মনে করা।
  • Client request body থেকে role গ্রহণ করা।
  • Authentication middleware-এর আগে role middleware চালানো।
  • Organizer role check করলেও event ownership verify না করা।
  • Expired token এবং invalid token সঠিকভাবে handle না করা।

Frontend permission controls are for user experience, but backend authorization is the actual security boundary.

RBAC Security Principle

15. Frequently Asked Questions (FAQ)

1. What is RBAC in Express.js?

RBAC হলো একটি authorization technique, যেখানে user-এর assigned role অনুযায়ী API access এবং permission control করা হয়।

2. What is the difference between authentication and authorization?

Authentication user-এর identity verify করে, আর Authorization নির্ধারণ করে authenticated user কোন resource বা action access করতে পারবে।

3. Why do we need RBAC middleware?

RBAC middleware API endpoint-এ role-based permission check করে। এতে unauthorized user restricted operation করতে পারে না।

4. Can an attendee create an event?

আমাদের current configuration অনুযায়ী পারবে না। কারণ event creation route-এ শুধু organizer role allowed করা হয়েছে।

5. What is the purpose of req.user?

req.user হলো request object-এর একটি property, যেখানে authentication middleware verified user information রাখে।

6. What does authorizeRoles("organizer") mean?

এটি এমন middleware তৈরি করে, যা শুধুমাত্র organizer role-এর authenticated user-কে পরবর্তী handler execute করতে দেয়।

7. Why do we use next()?

next() current middleware শেষ করে Express-এর পরবর্তী middleware বা route handler-এ control পাঠায়।

8. What is the difference between 401 and 403?

401 Unauthorized সাধারণত missing বা invalid authentication বোঝায়। 403 Forbidden বোঝায় user authenticated হলেও requested action-এর permission নেই।

9. Can one user have multiple roles?

হ্যাঁ। Application design অনুযায়ী user-এর একাধিক role থাকতে পারে। সেক্ষেত্রে database schema এবং authorization logic সেই অনুযায়ী তৈরি করতে হবে।

10. Is frontend role checking enough for security?

না। Frontend role checking শুধু UI control করে। Actual permission check অবশ্যই backend API-তে করতে হবে।

11. Why should we not trust the role sent by the client?

কারণ client সহজেই request modify করতে পারে। Role অবশ্যই trusted server-side database থেকে নিতে হবে।

12. What is resource ownership validation?

এটি check করে user যে resource update বা delete করতে চাচ্ছে, সেটি তার নিজের কি না। যেমন organizer শুধু নিজের event manage করতে পারবে।

16. Practical Assignment

এখন নিজের হাতে একটি Event Management API তৈরি করুন এবং নিচের tasks complete করুন:

  • Admin, Organizer এবং Attendee roles তৈরি করুন।
  • User Registration এবং Login API তৈরি করুন।
  • JWT access token generate করুন।
  • JWT Authentication middleware তৈরি করুন।
  • Reusable RBAC authorization middleware তৈরি করুন।
  • শুধুমাত্র Organizer-কে Event Create করার permission দিন।
  • Attendee-কে Event Registration করার permission দিন।
  • Admin-কে প্রয়োজনীয় management permission দিন।
  • Organizer যেন শুধু নিজের Event update এবং delete করতে পারে তা implement করুন।
  • Postman দিয়ে সব role test করুন।

Expected API Permission Matrix

API Endpoint Admin Organizer Attendee
POST /api/events Allow Allow Deny
GET /api/events Allow Allow Allow
PATCH /api/events/:id Allow Own Events Deny
DELETE /api/events/:id Allow Own Events Deny
POST /api/events/:id/register Optional Optional Allow

Note: এই permission matrix একটি example project design। আপনার application-এর business rules অনুযায়ী permission পরিবর্তন করতে পারবেন।

17. Useful Learning Resources

Conclusion

Role-Based Authorization (RBAC) হলো Express.js application-এর একটি গুরুত্বপূর্ণ security feature। Authentication middleware JWT verify করে user-এর identity নিশ্চিত করে, আর Authorization middleware user-এর role অনুযায়ী permission control করে।

আমাদের Event Management API-তে organizer account Event Creation API access করতে পারছে, কিন্তু attendee account 403 Forbidden response পাচ্ছে। এভাবেই reusable middleware ব্যবহার করে application-এর বিভিন্ন API endpoint secure করা যায়।

একটি production-ready application তৈরি করতে RBAC-এর পাশাপাশি database-level validation, resource ownership verification, secure JWT handling এবং proper error handling implement করতে হবে।

Post a Comment

To avoid SPAM, all comments will be moderated before being displayed.
Don't share any personal or sensitive information.