0Pricing
Node.js Backend Development Bootcamp · บทเรียน

การควบคุมการเข้าถึงตามบทบาท

พัฒนามิดเดิลแวร์สำหรับการอนุญาตสิทธิ์ โดยจำกัดการเข้าถึงเส้นทาง API ตามบทบาทและสิทธิ์ของผู้ใช้

การควบคุมการเข้าถึงตามบทบาท เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 5 จากทั้งหมด 6 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 6 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to Role-Based Access Control

Welcome! In this lesson, we'll dive into Role-Based Access Control (RBAC). RBAC is a method of restricting system access based on the roles individual users have within an organization.

Think of it like a set of keys: each key (role) grants access to specific doors (resources or actions). Instead of giving each person a key to every door, you give them a keyring based on their job.

Importance of RBAC

RBAC is crucial for building secure and scalable applications. It offers several benefits:

  • Improved Security: Users only access what they need.
  • Simplified Management: Easier to manage permissions for groups rather than individuals.
  • Reduced Errors: Less chance of granting incorrect access.
  • Enhanced Compliance: Helps meet regulatory requirements for data access.

Without RBAC, managing permissions in a growing application becomes a nightmare!

Roles & Permissions Defined

It's important to understand the difference between roles and permissions:

  • Role: A collection of permissions. Examples: Admin, Editor, Viewer, Guest.
  • Permission: A specific action a user can perform. Examples: read:post, write:post, delete:user.

A user is assigned one or more roles, and each role has a set of defined permissions. This structure makes access control flexible.

How to Store User Roles

When a user registers or logs in, their assigned roles need to be stored. Common ways to do this include:

  • Database Field: A string (e.g., "admin", "user") or an array of strings (e.g., ["admin", "editor"]) in the user's document/record.
  • JWT Payload: Include the roles directly in the JSON Web Token (JWT) during login. This makes them easily accessible on each request.

For our examples, we'll assume roles are available on the req.user object, which would be populated by a preceding authentication middleware (like one from a previous lesson).

Authorization Middleware Flow

In Express.js, middleware functions are perfect for authorization. An authorization middleware sits between the request and the route handler.

Here's how it works:

  1. A request comes in for a protected route.
  2. Our authorization middleware runs.
  3. It checks if the authenticated user has the necessary role(s).
  4. If yes, it calls next() to pass control to the route handler.
  5. If no, it sends an error response (e.g., 403 Forbidden).

Define Role Check Middleware

We'll create a reusable middleware function that checks if an authenticated user has a specific role. This function accepts the requiredRole as an argument and returns another middleware function.

A real application would first have an authentication middleware populating req.user.

function authorizeRoles(requiredRole) {
  return (req, res, next) => {
    // Assume req.user is populated by auth middleware
    // e.g., req.user = { id: 'abc', roles: ['user', 'editor'] }
    if (!req.user || !req.user.roles || !req.user.roles.includes(requiredRole)) {
      console.log(`Access Denied: Missing role '${requiredRole}'`);
      return res.status(403).send('Forbidden: Insufficient role');
    }
    console.log(`Access Granted for role '${requiredRole}'`);
    next(); // User has the required role, proceed
  };
}

// To make it runnable for demonstration, let's wrap it in a mock Express-like setup
const mockReq = { user: { id: '123', roles: ['user', 'admin'] } };
const mockRes = {
  status: function(code) { this.statusCode = code; return this; },
  send: function(msg) { console.log(`Response Status: ${this.statusCode}, Message: ${msg}`); }
};
const mockNext = () => console.log('Next middleware/route handler called.');

console.log('--- Testing authorizeRoles("admin") ---');
const adminAuth = authorizeRoles('admin');
adminAuth(mockReq, mockRes, mockNext);

console.log('\n--- Testing authorizeRoles("guest") ---');
const guestAuth = authorizeRoles('guest');
guestAuth(mockReq, mockRes, mockNext);

Protecting Routes with RBAC

Now, let's see how to apply our authorizeRoles middleware to protect specific routes in an Express.js application.

We can pass the middleware function directly to a route definition. Any request to that route will first pass through the authorization check.

const express = require('express');
const app = express();

// Mock authentication middleware (from previous lessons)
app.use((req, res, next) => {
  // In a real app, this would verify a JWT and populate req.user
  req.user = { id: 'user123', roles: ['user', 'viewer'] };
  next();
});

// Our authorization middleware
function authorizeRoles(requiredRole) {
  return (req, res, next) => {
    if (!req.user || !req.user.roles.includes(requiredRole)) {
      return res.status(403).send('Forbidden: Insufficient role');
    }
    next();
  };
}

// Route accessible only by 'admin'
app.get('/admin-panel', authorizeRoles('admin'), (req, res) => {
  res.send('Welcome to the Admin Panel!');
});

// Route accessible by 'user' or 'viewer' (since req.user has 'user', 'viewer')
app.get('/my-profile', authorizeRoles('user'), (req, res) => {
  res.send(`Hello ${req.user.id}, this is your profile.`);
});

app.listen(3000, () => {
  console.log('Server running on port 3000. Try accessing /admin-panel or /my-profile');
});

Handling Multiple Required Roles

Sometimes a route might be accessible by more than one role (e.g., an Editor or an Admin). We can extend our middleware to accept multiple required roles.

The user just needs to have *at least one* of the specified roles to gain access.

const express = require('express');
const app = express();

// Mock authentication middleware
app.use((req, res, next) => {
  req.user = { id: 'editor456', roles: ['user', 'editor'] };
  next();
});

// Middleware to check for multiple roles
function authorizeAnyRole(requiredRoles) {
  return (req, res, next) => {
    if (!req.user || !req.user.roles) {
      return res.status(403).send('Forbidden: User roles not found');
    }
    const hasRequiredRole = req.user.roles.some(role =>
      requiredRoles.includes(role)
    );
    if (!hasRequiredRole) {
      return res.status(403).send('Forbidden: Insufficient role(s)');
    }
    next();
  };
}

// Route accessible by 'admin' OR 'editor'
app.get('/edit-content', authorizeAnyRole(['admin', 'editor']), (req, res) => {
  res.send('You can edit content!');
});

// Route accessible by 'admin' only
app.get('/delete-all', authorizeAnyRole(['admin']), (req, res) => {
  res.send('Danger Zone: All data deleted!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000. Try /edit-content or /delete-all');
});

Beyond Roles: Granular Permissions

While roles are great for grouping permissions, sometimes you need more granular control. This is where explicit permissions come in.

  • Instead of authorizeRoles('admin'), you might have authorizePermission('delete:user').
  • Your user object would then store an array of specific permissions (e.g., ['read:post', 'update:post', 'delete:comment']).

This approach offers maximum flexibility but can increase complexity in managing permissions.

Check Your Understanding

Consider the following Express route setup:

// ... (assume authorizeRoles function is defined as in lesson)
app.use((req, res, next) => {
  req.user = { id: 'testUser', roles: ['user', 'moderator'] };
  next();
});

app.get('/moderate', authorizeRoles('moderator'), (req, res) => {
  res.send('Moderator access granted.');
});

app.get('/admin-only', authorizeRoles('admin'), (req, res) => {
  res.send('Admin access granted.');
});

Recap & Next Steps

Great job! You've learned how to implement Role-Based Access Control in your Node.js applications using Express.js middleware.

  • RBAC restricts access based on user roles.
  • Middleware functions are ideal for checking roles before route access.
  • You can check for single roles or multiple roles.
  • Advanced scenarios might involve direct permission checks.

Proper authorization is key to securing your API. Keep practicing to master these concepts!

คำถามที่พบบ่อย

บทเรียน “การควบคุมการเข้าถึงตามบทบาท” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การควบคุมการเข้าถึงตามบทบาท” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 6 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การควบคุมการเข้าถึงตามบทบาท”

พัฒนามิดเดิลแวร์สำหรับการอนุญาตสิทธิ์ โดยจำกัดการเข้าถึงเส้นทาง API ตามบทบาทและสิทธิ์ของผู้ใช้ คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 5 จากทั้งหมด 6 บทเรียน

บทเรียน “การควบคุมการเข้าถึงตามบทบาท” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การลงทะเบียนและเข้าสู่ระบบผู้ใช้
  2. การสร้างและตรวจสอบโทเค็น JWT
  3. JWT สำหรับการยืนยันตัวตนแบบไร้สถานะ
  4. การผสานรวมโฟลว์รหัสผ่าน OAuth2
  5. การควบคุมการเข้าถึงตามบทบาท
  6. การควบคุมการเข้าถึงตามบทบาท (RBAC)
← กลับไปที่ Node.js Backend Development Bootcamp