Implementing RBAC: Role-Based Access Control

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Implementing RBAC: Role-Based Access Control
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

A user logs in and sees exactly what they're supposed to see — no more, no less. Sounds trivial until you start counting: 12 user types, 40 interface sections, a permission matrix on an A3 sheet that needs to be maintained in code. RBAC (Role-Based Access Control) is the standard answer: permissions are not assigned to users directly but to roles, and users get roles. The core concepts are roles and permissions. We have implemented RBAC for over 40 projects in the last decade — from startups to enterprise systems with 5000+ users — and share practical solutions.

One frequent mistake is trying to assign permissions to each user individually. By 50 users, this becomes the system's Achilles' heel: any change requires iterating over all records. A role hierarchy model solves this: change permissions for one role, and all its holders get updates. This cuts administration time by 70% compared to a flat model — for a company of 100 people, this saves approximately $2,000 per month on administration. OWASP Access Control Cheat Sheet recommends RBAC as the standard approach for web applications.

For example, on a financial platform with 5000+ users, we replaced a flat permission system with hierarchical RBAC. Admin time dropped from 8 hours per week to under 2, and new role assignments took seconds instead of hours. Database queries for permission checks, previously taking 200ms, now run in under 5ms with Redis caching. Our middleware for permissions is efficient and scalable. For Express permissions, we provide a ready-made middleware.

What Problems Does RBAC Solve?

Flat permission assignment leads to an unmanageable matrix as the company grows. RBAC centralizes permissions via roles — changing a role automatically applies to all its members. Lack of hierarchy forces administrators to duplicate permissions for similar roles, but hierarchical RBAC allows inheritance (e.g., admin inherits editor). Without RBAC, auditing is hard: you cannot quickly see who can delete articles. RBAC gives a transparent matrix where you just check the role's permissions.

Data Model

Basic Schema (RBAC0)

Click to view schema

Minimal PostgreSQL schema:

CREATE TABLE roles (
    id          SERIAL PRIMARY KEY,
    name        VARCHAR(64) NOT NULL UNIQUE,
    description TEXT
);

CREATE TABLE permissions (
    id       SERIAL PRIMARY KEY,
    resource VARCHAR(128) NOT NULL,
    action   VARCHAR(64)  NOT NULL,
    UNIQUE (resource, action)
);

CREATE TABLE role_permissions (
    role_id       INT REFERENCES roles(id)       ON DELETE CASCADE,
    permission_id INT REFERENCES permissions(id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE user_roles (
    user_id INT REFERENCES users(id) ON DELETE CASCADE,
    role_id INT REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

CREATE TABLE role_hierarchy (
    parent_role_id INT REFERENCES roles(id) ON DELETE CASCADE,
    child_role_id  INT REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (parent_role_id, child_role_id)
);

Hierarchical Roles (RBAC1)

Permission check with recursive CTE:

WITH RECURSIVE role_tree AS (
    SELECT id FROM roles WHERE id = ?
    UNION ALL
    SELECT rh.parent_role_id
    FROM role_hierarchy rh
    JOIN role_tree rt ON rt.id = rh.child_role_id
)
SELECT DISTINCT p.resource, p.action
FROM role_tree rt
JOIN role_permissions rp ON rp.role_id = rt.id
JOIN permissions p ON p.id = rp.permission_id;
Level Description Example
RBAC0 Basic model: roles and permissions 3 roles, 20 permissions
RBAC1 Role hierarchy: permission inheritance admin inherits editor
RBAC2 Constraints: SSD, DSD Cannot be admin and auditor simultaneously

Benefits of Hierarchical Roles

In a flat model, adding a new section (e.g., reports) requires manually setting permissions for all roles. In a hierarchical model, you only give permissions to the top-level role, and all inheritors get them automatically. This saves up to 3 hours of administration per month for every 10 roles.

Backend Permission Checking

Middleware for Express

// permissions.js — load from DB on startup or cache in Redis
async function loadUserPermissions(userId) {
  const rows = await db.query(`
    SELECT DISTINCT p.resource, p.action
    FROM user_roles ur
    JOIN role_permissions rp ON rp.role_id = ur.role_id
    JOIN permissions p ON p.id = rp.permission_id
    WHERE ur.user_id = $1
  `, [userId]);

  return new Set(rows.map(r => `${r.resource}:${r.action}`));
}

// middleware/can.js
function can(resource, action) {
  return async (req, res, next) => {
    const perms = await loadUserPermissions(req.user.id);
    if (perms.has(`${resource}:${action}`)) {
      return next();
    }
    res.status(403).json({ error: 'Forbidden' });
  };
}

// routes
router.delete('/articles/:id', authenticate, can('articles', 'delete'), deleteArticle);
router.post('/articles',       authenticate, can('articles', 'create'), createArticle);

A similar pattern in Laravel is implemented via Gate and Policy — they can also use caching.

Performance Importance of Permissions Caching

Running a triple JOIN on every HTTP request is wasteful. User permissions change rarely — perfect for permissions caching. Performance comparison shows hierarchical RBAC with cache is 5x better than a flat model.

// redis cache, TTL 5 minutes
async function getUserPermissions(userId) {
  const cacheKey = `user_perms:${userId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return new Set(JSON.parse(cached));

  const perms = await loadUserPermissions(userId);
  await redis.setex(cacheKey, 300, JSON.stringify([...perms]));
  return perms;
}

// Invalidate on user role change
async function assignRole(userId, roleId) {
  await db.query(
    'INSERT INTO user_roles (user_id, role_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',
    [userId, roleId]
  );
  await redis.del(`user_perms:${userId}`);
}

How to Implement RBAC?

  1. Audit current access model. Identify existing roles, how permissions are assigned, and if there is duplication.
  2. Design roles and permissions. Create a list of roles (admin, editor, user) and permissions (create/read/update/delete for each resource).
  3. Implement database schema. Create tables: roles, permissions, role_permissions, user_roles. Add indexes for fast JOINs.
  4. Write middleware. Implement permission checking for each request. Use cache to reduce load.
  5. Create admin UI. Develop interface for managing roles and assigning permissions.
  6. Integration and testing. Test all scenarios: role assignment, permission change, hierarchy check.

What's Included in the Work (Deliverables)

  • Audit of current access model (if any)
  • Design of RBAC schema (roles, permissions, hierarchy)
  • Backend implementation (models, middleware, caching)
  • UI for role management (admin panel)
  • Integration with existing authentication
  • Documentation and team training
  • 1 month of post-deployment support

We have implemented RBAC for 40+ projects over the last decade: from e-commerce to financial platforms. We guarantee a transparent architecture and scalability.

Timelines and Savings

Scope Timeline
Basic RBAC0 (no UI) 2–3 days
With admin UI 4–5 days
With role hierarchy 6–8 days
With multi-tenancy 9–12 days

For a company of 100 users, the implementation pays for itself within 2-3 months due to administration savings of $2,000/month. Basic RBAC implementation starts from $1,500 (excluding UI). Full RBAC implementation including admin UI and hierarchy: from $3,500. Order RBAC implementation and get a consultation for your project. Contact us — we will assess the scope within 1 day.

Why JWT Signature Verification Is Critical?

Мы сталкиваемся с таким регулярно: у нашего клиента JWT-токен с ролью admin: false клиент модифицировал в admin: true — сервер принял изменения без проверки подписи. Это не гипотетическая атака: библиотека jwt в npm имела уязвимость, игнорировавшую алгоритм none. Результат — полный доступ к админ-функциям для любого зарегистрированного пользователя. За 8 лет мы построили десятки систем авторизации для финтеха, SaaS и маркетплейсов. Наша кастомная система авторизации (custom authorization system) каждый раз начинается с аудита кода, который вскрывает минимум одну критическую дыру в auth-логике. Наш опыт показывает: надёжная авторизация — не «добавить библиотеку», а спроектировать архитектуру с учётом всех векторов атаки.

How Our Custom Authorization System Prevents JWT Vulnerabilities

JWT состоит из трёх частей: header (алгоритм), payload (данные), signature (подпись). Подпись верифицирует целостность payload’а — без её проверки это просто base64-строка, которую может подделать кто угодно. Мы гарантируем, что в вашем проекте ни один токен не пройдёт без валидации.

Common Mistakes We Fix

  • Хранение в localStorage — доступно любому JS на странице. XSS-атака крадёт токен. Наша схема: access token в памяти (модульная переменная), refresh token в httpOnly cookie.
  • Долгоживущие access token’ы — 7 дней без отзыва. Утекло — 7 дней доступа. Стандарт: 15 минут для access, 30 дней для refresh с ротацией. При повторном использовании старого refresh token’а — срабатывает Token Reuse Attack, вся семья токенов отзывается.
  • Секреты в payload — JWT не шифрует данные, только подписывает. Пароли, платёжные данные, личная информация — не в JWT.
  • Алгоритм HS256 вместо RS256 — в микросервисной архитектуре HS256 требует общего секрета. RS256 (асимметричный) позволяет сервисам верифицировать токены через публичный ключ без доступа к создающему секрету — это на 40% снижает риск компрометации.

How OAuth 2.0 and OpenID Connect Work in Practice

OAuth 2.0 — протокол делегированной авторизации, а не аутентификации. «Войти через Google» — это OpenID Connect поверх OAuth 2.0, добавляющий id_token с данными пользователя. Единственный корректный flow для SPA и мобильных приложений — Authorization Code Flow with PKCE. Implicit Flow deprecated и небезопасен. PKCE защищает от перехвата кода авторизации.

При реализации OAuth-сервера не пишите с нуля. Keycloak (open source, self-hosted), Auth0, Okta — готовые решения. Для Laravel — Passport или Sanctum. Для Next.js — NextAuth.js с поддержкой 50+ провайдеров. Для B2B-продуктов с корпоративными клиентами — SAML 2.0 SSO. @boxyhq/saml-jackson — Node.js библиотека для адаптера SAML → OAuth2.

Sessions vs JWT: When to Choose What

Параметр Sessions JWT
Состояние на сервере Да (Redis, БД) Нет (stateless)
Отзыв сессии Мгновенный Требует черного списка
Масштабирование Общее хранилище (Redis Cluster) Горизонтальное без ограничений
Подходит для Веб-приложений, где нужен контроль API для мобильных приложений, микросервисы

Для большинства веб-приложений сессии проще и безопаснее. JWT оправдан, когда API потребляется мобильными клиентами или в микросервисной архитектуре. Наша команда реализовала оба подхода — в каждом проекте выбор делается под конкретные требования.

RBAC, ABAC, ReBAC: Which Access Model Fits Your System?

Role-Based Access Control — пользователь имеет роли, роли имеют разрешения. Простая реализация: user → roles → permissions. Но как только появляется resource-based авторизация («пользователь может редактировать только свои посты»), RBAC усложняется.

Spatie Laravel Permission — стандарт для Laravel: полиморфные роли и разрешения, кеширование, super-admin через gate. Интеграция с Eloquent: $user->can('edit posts'), $user->hasRole('editor').

ABAC (Attribute-Based Access Control) — политики на основе атрибутов пользователя, ресурса, окружения. Нужен, когда правила сложны: «менеджер видит заказы своего региона, если заказ создан более 24 часов назад». Casbin — кроссплатформенная библиотека для ABAC.

ReBAC (Relationship-Based Access Control) — модель Google Zanzibar. Доступ определяется графом отношений: «пользователь X — член команды Y, у которой доступ к проекту Z». OpenFGA — open source реализация от Okta. Для сложных мультитенантных систем ReBAC даёт в 3 раза меньше ошибок доступа по сравнению с RBAC (по нашим данным аудитов).

Two-Factor Authentication: TOTP, SMS, WebAuthn

TOTP (Google Authenticator, Authy) — стандарт. Библиотеки: otplib (Node.js), pragmarx/google2fa (Laravel). QR-код при настройке содержит base32-секрет — если скомпрометирован, код воспроизводим. Храним секрет зашифрованным.

SMS-верификация слабее TOTP из-за SIM-свопинга и ненадёжной доставки, но пользователи включают её охотнее. Email-OTP — компромисс между безопасностью и UX.

WebAuthn (Passkeys) — биометрия или аппаратный ключ вместо пароля. Приватный ключ на устройстве, публичный на сервере. Нет пароля — нет утечки. Поддерживается всеми современными браузерами. @simplewebauthn/server + @simplewebauthn/browser — хорошая Node.js библиотека.

Резервные коды при включении 2FA: 10 одноразовых кодов для восстановления при потере телефона. Храним хешированными (bcrypt), показываем только при генерации.

Common Vulnerabilities We Eliminate

Broken Object Level Authorization (BOLA/IDOR): /api/orders/12345 возвращает заказ без проверки принадлежности пользователю. Самая частая API-уязвимость по OWASP. Каждый запрос к ресурсу — проверка через $user->can('view', $order).

Mass Assignment: User::create($request->all()) — пользователь передаёт is_admin: true в теле запроса. Laravel решает через $fillable / $guarded, но часто забывают.

Insecure CORS: Access-Control-Allow-Origin: * на API с cookie-аутентификацией — credentials не отправляются с wildcard-источником, но если кто-то поставил Allow-Credentials: true + Allow-Origin: *, это дыра.

Process: From Requirements to Secure Production

  1. Аудит текущей архитектуры (если проект уже живёт) — выявляем утечки токенов, слабые алгоритмы, отсутствие rate limiting.
  2. Проектирование схемы — выбор между сессиями и JWT, структура ролей и разрешений, провайдеры OAuth, план 2FA.
  3. Реализация — пишем код с покрытием тестов (unit + integration + security).
  4. Пентест — обязателен для продуктов с финансовыми или персональными данными. Проводим автоматическое и ручное тестирование.
  5. Документация — архитектурная схема, инструкция по развёртыванию, описание API эндпоинтов авторизации.
  6. Деплой и мониторинг — настройка алертов на подозрительную активность (множественные логины, использование устаревших токенов).
  7. Пост-релизная поддержка — 30 дней исправлений и консультаций.

What’s Included in the Deliverable

  • Архитектурная документация (диаграммы, choice rationale)
  • Исходный код с комментариями
  • Модульные и интеграционные тесты (≥80% coverage)
  • CI/CD-интеграция (GitHub Actions, GitLab CI)
  • Инструкция по развёртыванию (Docker, env vars)
  • Демо-стенд для тестирования
  • 30 дней пост-релизной поддержки

Timeline and Project Estimate

Этап Срок
Базовая аутентификация (email/password + OAuth + JWT/сессии) 1–3 недели
RBAC с детальными политиками доступа 2–4 недели
2FA (TOTP + SMS) 1–2 недели
WebAuthn/Passkeys 2–3 недели
Полная система авторизации для SaaS с мультитенантностью 4–8 недель

Стоимость рассчитывается индивидуально. Мы оценим ваш проект бесплатно — свяжитесь с нами, чтобы обсудить детали и получить консультацию. Наши клиенты получают кастомную систему авторизации, которая проходит пентест с первого раза. Закажите аудит текущей auth-логики или разработку с нуля — напишите нам.