How to Implement Role-Based Access Control in B2B Marketplaces

How to Implement Role-Based Access Control in B2B Marketplaces

The access control problem in a B2B marketplace goes beyond ordinary multi-tenant RBAC. Here, buyers and suppliers share some records, while others should stay private to one organization. In any case, there’s one main rule every system must enforce: nobody should see more than the job requires.

Follow along in this article while we explore how to design role-based access control (RBAC) for that setup. We’ll skip the basics from any RBAC tutorial since our main focus will be in the marketplace. We’ll discuss organization-level roles, permission storage, tenant data isolation, purchase approvals, and back-end checks as the main topics.

Why RBAC in B2B Marketplaces is Different

When teams build a single-company app, role definition is pretty straightforward. And an admin is an admin and a viewer is a viewer. Now let’s consider the following example for the marketplace scenario: Dana is a purchasing manager at a buyer company, but she’s also helping a friend’s small firm that sells on the same platform. For both cases, she uses the same account within the platform, so you could not store a single, global role field attached to the user. Instead, roles need to be attached to a membership which links one user to one organization.

Unlike the textbook RBAC model that links users to roles and roles to permissions, the example above incorporates the organization scope on top. Each check the system does needs to answer two questions:

  • Does this person hold the permission?
  • Does it apply in this organization?

Visibility is another aspect where the marketplace differs from traditional models; it often crosses company lines. For instance, a buyer sees supplier catalogs and quotes, but not cost data. A supplier sees incoming orders, but not the buyer’s internal approval notes. Platform staff also need support access. This requires an audit and an explicit expiration date. State also shapes permissions, because an order in a specific status (such as draft) can be edited, whereas it should be read-only in other ones (like confirmed).

Organization-Level Access Control

Several teams try to start by creating several roles from the first day. That’s probably a mistake because as the system evolves, they’d find most of them will overlap. A better approach starts with a small set of roles per organization type. For instance, a buyer organization can start with five roles: An owner to manage billing and members. The purchaser who creates carts and orders. The approver signs off on orders above a threshold. And a viewer who reads orders and invoices. Supplier organizations might need an owner to manage members and payout details, a catalog manager in charge of editing products and price lists, a sales rep that answers quotes and RFQs, a fulfillment role to update shipment status, and a finance role to read invoices and payouts.

While names may vary depending on the organization type, permission keys should not. The role is just a named bundle of those keys. The following example shows a buyer-side matrix of marketplace user permissions:

Permission Purchaser Approver Viewer
order.create yes no no
order.approve no yes no
order.view yes yes yes
invoice.view no yes yes

Platform roles need a separate scope that typically includes support agent, compliance reviewer, and platform admin. Those roles should live outside the organization role table.

Large customers may ask for custom roles. Compose them with the existing permission keys instead of inventing new ones. A permission key is a contract with your code, so this has to be honored no matter how things evolve.

Database Design

Chudovo’s team starts with five tables for this model. They treat org_id as a nullable field: NULL means a system role that’s shared by all organizations, whereas a value in such a column implies a custom role owned by one organization. The UNIQUE (user_id, org_id) constraint blocks duplicate membership rows.

A validation should happen each time a custom role is assigned. It has to ensure its org_id matches the membership’s organization; shared roles must also match the organization type: buyer or supplier. All those validations should happen in the service layer, since the foreign keys mentioned above do not enforce either rule. It’s also important to check which roles the acting administrator is allowed to grant to prevent privilege escalation.

Permission keys should be kept as plain strings in role_permissions because a separate permissions table not only looks tidy but also adds a join and a migration step for little gain.

The sketch below uses PostgreSQL syntax:

CREATE TABLE organizations (
id uuid PRIMARY KEY,
type text NOT NULL CHECK (type IN ('buyer', 'supplier')),
name text NOT NULL
);
​
CREATE TABLE memberships (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id),
org_id uuid NOT NULL REFERENCES organizations(id),
status text NOT NULL DEFAULT 'active',
UNIQUE (user_id, org_id)
);
​
CREATE TABLE roles (
id uuid PRIMARY KEY,
org_id uuid REFERENCES organizations(id), -- NULL = system role
name text NOT NULL
);
​
CREATE TABLE role_permissions (
role_id uuid REFERENCES roles(id),
permission text NOT NULL,
PRIMARY KEY (role_id, permission)
);
​
CREATE TABLE membership_roles (
membership_id uuid REFERENCES memberships(id),
role_id uuid REFERENCES roles(id),
PRIMARY KEY (membership_id, role_id)
);

Multi-Tenant Data Isolation

When it comes to managing tenant data, teams could use shared tables with an org column, one schema per tenant, or one database per tenant.

Let’s consider the two latest options first from a practical standpoint: if an order has to have two owners, and both the buyer organization and the supplier organization must read it. With one schema-per-tenant, the row lives in one schema and has to be visible from another. That’s painful. The third option is even worse. If a row living in a different schema causes a severe headache, a row living in a completely separate database introduces a massive infrastructure and engineering wall.

This leads us towards the shared tables as the right pick. Under this approach, each shared row carries both a buyer_org_id and supplier_org_id. The caller’s organization is used in every query’s filter. 

For mutli-tenants applications, PostgreSQL Row-Level Security could be added at row-level security. This way, the query will only return rows allowed by the policy with no need fot specific organization filters in the query itself.  The tradeoff here is that queries become harder to debug, so this has to be measured on each project’s data before the actual implementation comes in. Another thing to keep in mind is that these policies only work for read access control, so to restrict the write actions that each organization could perform, teams need to establish separate policies. 

Every transaction should set app.org_id with SET LOCAL to prevent the settings from one tenant to apply to a different one. This is because in pooled connections a plain SET can carry one request’s tenant into the next. On the other hand, it’s recommended to not rely on the frontend to hide fields. The frontend might apply its own rules to decide what information to display, but that should not be considered an enforcement rule. A better approach is to handle different displays in serializers or database views, with one response shape per side.

Purchasing Approval Workflows

Let’s assume we created a permission that says a purchaser can submit orders with an approval policy for orders above $5,000. Whenever a purchaser creates an order that exceeds the threshold, the order moves to pending_approval. An approver reviews it, and only then does the order reach the supplier.

Purchase Approval Workflow in B2B Marketplaces

Thresholds belong to data, not roles. An approval_policies table holds org_id, requires_approval_above, max_approval_amount, currency, and approver_role_id. Use the first amount to determine whether a review is required; the second one the second caps what that role may approve. Currency is used to standardize the comparison. Do not use the amounts to provide roles’ names (such as “Approver up to 5k” and “Approver up to 20k”) because that ends in a role explosion within a year. As a general rule, enforce separation of duties in a way that the person who created an order cannot approve it; single-user organizations might need a separate, explicitly defined exception policy.

Back-end Checks for B2B Marketplace Authorization

Controllers and UI code could have checks, but the service layer should be the real enforcer because it is the only one that always runs. Chudovo’s team usually implements an authorization method that first looks for a membership for the provided combination of user and organization IDs. If no match is found, an early exception is thrown. Otherwise, the system looks into the permissions that membership has and compares it with the one required to access the specific resource. If the resource should not be accessible, a 404 error is returned (instead of 401/403, which confirms the row exists).

The method above could be called when the system needs to execute an action, for instance, when an order needs to be approved and before any transition.

The same database transaction should contain the order read, the approval checks, and the transition. To prevent an order from changing between review and approval, it should be locked before reading it; the same applies to changes to order totals or line items.

The client usually sends an active org ID for those users that belong to several organizations. That input should not be  blindly trusted and should always be validated server-side against the user’s memberships on every request. Do not read that input from the request body; it’s better to pick that ID from the session.

Long-lived JWTs should not carry permissions because a removed member keeps access until the token expires. Invalid tenant access should return 404 instead of 403, because the latter tells attackers the resource exists and helps them enumerate order numbers.

Cache could be applied to permissions for a short time; it has to be invalidated whenever the active role changes.

The measures above also apply to background jobs; otherwise the job becomes a way around your RBAC layer.

Common Security Mistakes

Most of the marketplace code across different projects usually shows some common mistakes. The most relevant one is to rely on the UI instead of implementing proper checks on the server side. We already discussed trusting org_id from the request body or a query parameter instead of taking that information from the session in one we already mentioned. That’s not the only one. UI often includes display logic that hides buttons, filters, or some information based on a specific state, and some teams rely on that logic as a security gate. A strong system enforce security policies in the back-end independently of any rendering decision.

Another common pitfail is to protect only the orders but forget nested objects. Imagine a team that protects GET /orders/:id carefully, but exposes as GET /attachments/:id, which takes only an attachment ID, with no check running on each request. OWASP calls this broken object-level authorization, and it sits at the top of the OWASP API Security list. How to fix it? Just route every object lookup through a single function that takes the caller’s org and ban direct findById calls in handlers.

Other frequent mistakes include:

  • storing one global role on the user record
  • leaving API keys and webhooks unscoped (so one key reads every organization)
  • giving support staff permanent access with no audit trail. 

Teams often realize this after the code has lived in production for a while.

Where to Іtart

If you’re asking where to start building role-based access control in B2B marketplaces, probably the best answer is to do it in steps. Start small, with five tables and one authorized function. In most cases, that get you far; otherwise, you can scale the project up based on the specific needs. 

In all cases, proper testing has to be included from the beginning. Cross-tenant tests are the most interesting ones. They are easy to run: just call every endpoint with an unrelated organization’s token against another organization’s data and expect a 404. Also, remember to test buyer and supplier permissions separately, because the fact that they could access to the same order should never imply permission to perform the same actions.

We use essential cookies to ensure our website works properly. With your consent, we also use optional cookies for analytics and other purposes. You can accept, reject, or customize your preferences. See our Cookie Policy.