Script Valley
Web Security Fundamentals for Developers
Access Control and AuthorizationLesson 5.2

Role-based access control (RBAC): designing and implementing permission systems

RBAC model, roles vs permissions, middleware-based enforcement, least privilege principle, role assignment, permission escalation prevention, casbin

Role-Based Access Control (RBAC)

RBAC model diagram

RBAC groups permissions into roles and assigns roles to users. It is the most common access control model for web applications because it's simple to reason about and audit.

Middleware-Based Role Enforcement

// Define roles and their permissions
const PERMISSIONS = {
  admin:    ['read:any', 'write:any', 'delete:any'],
  editor:   ['read:any', 'write:own'],
  viewer:   ['read:any']
};

// Middleware factory
function requirePermission(permission) {
  return (req, res, next) => {
    const userPermissions = PERMISSIONS[req.user.role] || [];
    const [action, scope] = permission.split(':');

    const hasPermission = userPermissions.some(p => {
      const [pAction, pScope] = p.split(':');
      return pAction === action && (pScope === 'any' || pScope === scope);
    });

    if (!hasPermission) {
      return res.status(403).json({ error: 'Insufficient permissions' });
    }
    next();
  };
}

// Usage
app.delete('/posts/:id',
  authenticate,
  requirePermission('delete:any'),
  deletePostHandler
);

Least Privilege

Assign the minimum role that allows a user to do their job. Don't give editor permissions to users who only need viewer access. Audit role assignments regularly—especially when users change teams.

Don't Store Roles in JWTs Without Careful Thought

If you store roles in a JWT and a user's role changes, the old JWT remains valid until it expires. For sensitive role changes (admin revocation), maintain a server-side role lookup so tokens always reflect the current role.

Up next

Mass assignment vulnerabilities: how to prevent field injection attacks

Sign in to track progress