RBAC and Endpoint-Level Access Control

Assign permissions through roles and check both permissions and ownership in endpoints

🎯 Introduction

By the end of this article, you will be able to assign permissions through roles and check both permissions and resource ownership in endpoints.

🧱 Users have roles; roles have permissions

RBAC means role-based access control. Define operations such as editing or deleting articles as permissions, grant sets of permissions to roles, and assign roles to users.

RoleAllowed operations
readerarticle:read
editorarticle:read, article:update
adminarticle:read, article:update, article:delete

Permission strings are identifiers defined by your project. Store user-role and role-permission relationships separately in the database instead of hard-coding “role equals admin” in every endpoint.


🔍 Write a focused permission check

Create permissions.mjs:

permissions.mjs
const permissions = {
    reader: ['article:read'],
    editor: ['article:read', 'article:update'],
    admin: ['article:read', 'article:update', 'article:delete']
};

export function hasPermission(actor, permission) {
    return actor.roles.some(role => permissions[role]?.includes(permission));
}

actor.roles must come from trusted server-side user records, not a client-submitted role array. true means the roles permit this type of operation; it does not yet establish ownership of a particular article.


🚪 Check operation permissions before the endpoint

Authentication middleware should first place a trusted user record in res.locals.user, such as { id: 1, roles: ['editor'] }. Add permission middleware to permissions.mjs:

permissions.mjs
export function requireArticleUpdate(req, res, next) {
    const user = res.locals.user;
    if (!user) return res.status(401).json({ error: 'Sign in first' });
    if (!hasPermission(user, 'article:update')) {
        return res.status(403).json({ error: 'You do not have permission to update articles' });
    }
    next();
}

Editors proceed to the next handler, readers receive 403, and unauthenticated users receive 401. Authentication middleware must obtain the user from a session or verified token rather than copying request roles into locals.


🔒 Then check article ownership

A role's permission to edit still requires checking target ownership. Define the business rule in the same file:

permissions.mjs
export function canEditArticle(user, article) {
    return user.roles.includes('admin') || article.ownerId === user.id;
}

article should come from a database query. This contract lets administrators edit across users, while ordinary editors can edit only their own articles. The update endpoint must run permission middleware, fetch the article, check ownership, and only then write to the database.


🧪 Test combinations of roles and ownership

Create permission-demo.mjs:

permission-demo.mjs
import { hasPermission, canEditArticle } from './permissions.mjs';

const editor = { id: 1, roles: ['editor'] };
console.log(hasPermission(editor, 'article:update'));
console.log(canEditArticle(editor, { ownerId: 1 }));
console.log(canEditArticle(editor, { ownerId: 2 }));

Running it prints true, true, false. The editor has update permission but should still receive 403 for another user's article.


⚠️ Apply permission changes promptly

After an administrator removes a role, do not trust roles in old tokens indefinitely. Sensitive operations can query current permissions, or use permission versions and short expiration to bound update delays.

Deny operations by default unless explicitly granted. Decide whether every new endpoint is public or protected; forgetting to register permissions must not make it public automatically.


❓ Questions and Answers

Q1: Can hiding menus replace RBAC?

No. Menus only display the result. Check permissions before executing the actual endpoint.

Q2: Does article:update allow editing every article?

Not necessarily. Operation permissions and data scope are separate checks. This article also restricts ownership.

Q3: Does every project need many roles?

No. Start with a few roles based on actual responsibilities, rather than inventing one for each user.


🧪 Practice

Add a reviewer role that can only read articles. Confirm that it fails article:update even for an article the user created.

// Write your code or record your verification results here