blog-hero-background-image
Cyber Security

Examples of Role Based Access Control (RBAC) - Pseudocode Included

backdrop
Table of Contents

Join thousands of professionals and get the latest insight on Compliance & Cybersecurity.


You've spent countless hours trying to implement access control from scratch. Hardcoding every case feels tedious, generalizing it with ORMs seems tricky, and you're still not sure how to handle users with multiple roles. Sound familiar?

"I have spent too much time trying to implement this on my own. I'm fairly new to SQL and Supabase so that's why it was hard for me," laments one developer on Reddit.

Another developer struggles with more complex scenarios: "RBAC will not work with the demands my tool has. It can be seen similarly on how in one drive you can share a sub folder or an individual file but leave the root folder untouched."

This guide will demystify Role-Based Access Control (RBAC) with concrete examples and practical pseudocode to help you bridge the gap from theory to implementation.

What is RBAC and Why Does It Matter?

Role-Based Access Control (RBAC) is a security model that restricts system access to authorized users based on their roles within an organization. Instead of assigning permissions directly to individual users, permissions are grouped into roles that align with job functions.

RBAC matters for three key reasons:

  1. Simplifies Administration: It eliminates the need to manage permissions for each user individually, reducing administrative workload and the chance of errors.
  2. Enforces Principle of Least Privilege (PoLP): Employees get access only to the information and tools needed for their jobs, minimizing data breach risks.
  3. Enhances Security & Compliance: Helps organizations comply with data protection regulations by providing transparency on who can access sensitive information.

Core Concepts: How RBAC Works

According to the NIST (National Institute of Standards and Technology) model, RBAC operates on three primary rules:

  1. Role Assignment: A user can exercise a permission only if they have been assigned a role.
  2. Role Authorization: A user's active role must be authorized for that user.
  3. Permission Authorization: A user can exercise a permission only if it's authorized for their active role.

The basic flow works like this:

  1. An administrator defines a role (e.g., "Editor").
  2. The admin assigns specific permissions to that role (e.g., "edit_content", "upload_content").
  3. Users are assigned to the "Editor" role.
  4. When a user tries to perform an action, the system checks their assigned role(s) and grants access only to the permitted actions.

Key components in an RBAC system include:

  • User: An individual or system entity.
  • Role: A collection of permissions based on job responsibilities.
  • Permission: The ability to perform a specific action on a resource.
  • Resource: The asset being protected (e.g., a database table, an API endpoint).

Real-World Examples of RBAC Across Industries

Let's examine how RBAC works in various contexts:

Healthcare Management System

  • Doctor: Can access and modify all patient records, prescribe medication, order tests.
  • Nurse: Can view and update patient vitals and notes. Cannot prescribe medication.
  • Billing Staff: Can only access patient demographic and billing information. Cannot view clinical notes.
  • Pharmacist: Can view and update prescription details.

Corporate IT System / SaaS Application

  • Administrator: Full access to create/configure/delete resources, manage user permissions, and configure security settings.
  • Developer: Can write, edit, and deploy code to staging environments. Read-only access to production logs. Cannot manage user accounts.
  • Data Analyst: Read-only access to query specific databases. Cannot modify data or manage database structure.
  • Marketing Manager: Access to marketing tools like HubSpot and Google Analytics. No access to source code or financial systems.

E-commerce Platform

  • Customer: Can view products, place orders, and view their own order history.
  • Merchant/Vendor: Can upload/edit their own product listings and view orders for their products. Cannot see other merchants' data.
  • Customer Support: Can view customer account info and order details to assist with issues. Cannot initiate transactions.
  • Platform Admin: Can manage all platform settings, view all orders and products, and update policies.

IoT Network (e.g., Smart Home)

A recent research paper on RBAC in IoT highlights its effectiveness, reporting a 99% security effectiveness rate.

  • Admin: Can add/remove devices, manage users, and view all data from all devices.
  • User (Homeowner): Can view data and control their own registered devices (e.g., adjust thermostat, turn on lights).
  • Guest: Read-only access to specific, non-sensitive data (e.g., view current temperature but not change it).

Implementing RBAC: A Step-by-Step Guide with Pseudocode

Now let's bridge the gap from theory to implementation with practical pseudocode examples.

Step 1: Defining Roles and Permissions

// Define permissions
const permissions = [
  'view_content',
  'edit_content',
  'delete_content',
  'upload_content',
  'manage_users',
  'manage_roles',
  'manage_settings'
];

// Define roles and their associated permissions
const roles = {
  'admin': ['view_content', 'edit_content', 'delete_content', 'upload_content', 'manage_users', 'manage_roles', 'manage_settings'],
  'editor': ['view_content', 'edit_content', 'upload_content'],
  'viewer': ['view_content']
};

Step 2: Defining User Roles

// Example user objects from your database
const users = [
  {
    id: 123,
    username: 'jane.doe',
    roles: ['editor', 'viewer'] // User has multiple roles
  },
  {
    id: 456,
    username: 'john.smith',
    roles: ['admin']
  },
  {
    id: 789,
    username: 'guest.user',
    roles: ['viewer']
  }
];

Step 3: Creating an Access Control Function

function hasPermission(user, requiredPermission) {
  // Iterate through each role the user has
  for (const role of user.roles) {
    // Get the permissions for the current role
    const permissionsForRole = roles[role];

    // If the role exists and includes the required permission, return true
    if (permissionsForRole && permissionsForRole.includes(requiredPermission)) {
      return true;
    }
  }
  // If no role grants the required permission, return false
  return false;
}

Step 4: Using the Function in Your Application

// Example of protecting an API endpoint in a server-side application
function editContentAPI(request, response) {
  const user = request.user; // Assume user is attached from auth middleware
  
  // Check for permission before proceeding
  if (!hasPermission(user, 'edit_content')) {
    return response.status(403).send('Forbidden: You do not have permission to edit content.');
  }
  
  // ... proceed with edit logic ...
  return response.status(200).send('Content edited successfully.');
}

// Example of conditional UI rendering in a client application
function RenderEditButton({ user, contentId }) {
  // Only show edit button if user has permission
  if (hasPermission(user, 'edit_content')) {
    return <button onClick={() => editContent(contentId)}>Edit</button>;
  }
  return null; // Don't render anything if user lacks permission
}

Step 5: Implementing Row Level Security (RLS) in a Database

For database-level access control, such as in Supabase or PostgreSQL:

-- Create a function to check if the current user has a specific permission
CREATE OR REPLACE FUNCTION has_permission(required_permission TEXT)
RETURNS BOOLEAN AS $$
DECLARE
  user_roles TEXT[];
  role_permissions TEXT[];
  r TEXT;
BEGIN
  -- Get the current user's roles from the JWT
  user_roles := current_setting('request.jwt.claims')::json->'roles';
  
  -- For each role, check if it has the required permission
  FOREACH r IN ARRAY user_roles LOOP
    -- Get permissions for this role from the roles table
    SELECT permissions INTO role_permissions FROM roles WHERE name = r;
    
    -- If the role has the required permission, return true
    IF required_permission = ANY(role_permissions) THEN
      RETURN TRUE;
    END IF;
  END LOOP;
  
  -- If no role has the permission, return false
  RETURN FALSE;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Apply RLS policy to a table
CREATE POLICY "Users can view content" ON content
  FOR SELECT
  USING (has_permission('view_content'));

CREATE POLICY "Editors can edit content" ON content
  FOR UPDATE
  USING (has_permission('edit_content'));

Beyond Basic RBAC: Addressing Complexity

While RBAC works well for many scenarios, it can be too rigid for certain use cases. As one developer noted, "RBAC will not work with the demands my tool has. It can be seen similarly on how in one drive you can share a sub folder or an individual file but leave the root folder untouched."

When RBAC isn't enough, consider these alternatives:

  • Attribute-Based Access Control (ABAC): More granular and context-aware. Grants access based on attributes of the user (e.g., department, location), the resource (e.g., data sensitivity), and the environment (e.g., time of day).
  • Relationship-Based Access Control (ReBAC): Controls access based on the relationships between users and resources (e.g., "User A can edit documents they own"). This directly addresses the file-sharing example.

RBAC Best Practices

  1. Principle of Least Privilege: Grant only the minimum permissions necessary for a role to function.
  2. Role Granularity: Define roles carefully. Avoid creating roles that are too broad (granting excessive permissions) or too narrow (leading to "role explosion").
  3. Separation of Duties: Differentiate roles to ensure no single user has conflicting permissions (e.g., the person who submits an expense report cannot also be the one to approve it).
  4. Periodic Reviews: Regularly audit user access rights and roles to remove unnecessary permissions, especially when employees change roles or leave the organization.
  5. Automate Provisioning: Use automated tools for access rights management to reduce manual errors and ensure consistency.

By implementing these rbac examples and best practices, you can create a robust access control system that balances security with usability and scales with your organization's needs.

Frequently Asked Questions (FAQ)

What is the main difference between RBAC and ABAC?

The main difference is that Role-Based Access Control (RBAC) grants permissions based on a user's job function or role, while Attribute-Based Access Control (ABAC) uses dynamic attributes of the user, resource, and environment to make more granular decisions. RBAC is simpler and assigns static permissions to roles like "Editor" or "Admin." In contrast, ABAC is more flexible and can enforce rules like "Allow marketing managers to access documents tagged 'marketing' only during business hours." Choose RBAC for straightforward, role-driven systems and ABAC for complex scenarios requiring context-aware logic.

How do you handle a user with multiple roles in RBAC?

To handle a user with multiple roles, you assign all relevant roles to the user's profile and aggregate the permissions from each role. The user effectively gains the combined access of all their assigned roles. For example, if a user has both "Editor" and "Viewer" roles, they can perform actions permitted by either role. When checking for access, your system should iterate through all of the user's roles and grant access if any of them contain the required permission. This approach provides flexibility without creating hyper-specific roles for every possible combination of duties.

What are permissions in the context of RBAC?

In RBAC, a permission is the authorization to perform a specific action on a particular resource. It is the most granular level of access control in the model. For instance, edit_content is a permission that allows a user to modify a piece of content. Permissions are grouped together to form a role. A role like "Editor" might contain permissions such as edit_content, view_content, and upload_content. Users are assigned roles, not individual permissions, which simplifies administration.

When is it better to use RBAC instead of other access control models?

It is better to use RBAC when your organization's access needs can be clearly defined by job functions or user roles. RBAC excels in environments with stable, hierarchical structures where simplicity and ease of administration are priorities. For most standard applications like corporate IT systems or content management systems, RBAC provides a robust and manageable solution. However, if your application requires highly dynamic rules (e.g., access based on location or time of day), a more granular model like ABAC or ReBAC might be a better fit.

How does Row Level Security (RLS) relate to RBAC?

Row Level Security (RLS) is a database feature that can be used to implement the data access policies defined by your RBAC model. It allows you to enforce RBAC rules directly within the database layer. With RLS, you create policies that check a user's role (often passed via a JWT) before allowing them to read, update, or delete specific rows in a table. This provides a powerful, low-level enforcement of your RBAC strategy.

What is the principle of least privilege in RBAC?

The principle of least privilege in RBAC means that a user should only be granted the minimum set of permissions necessary to perform their job duties. This is a core security concept that RBAC helps enforce. Instead of granting broad access, you define roles with only the essential permissions. For example, a "Billing Staff" role would have permission to view billing information but not clinical notes. This minimizes the potential damage from a compromised account and is a key best practice for building secure systems.

Remember, the right approach depends on your specific use case. For simpler applications, RBAC provides an excellent balance of security and simplicity. For more complex scenarios requiring contextual or relationship-based decisions, consider supplementing RBAC with ABAC or ReBAC principles.

toaster icon

Thank you for reaching out to us!

We will get back to you soon.