Skip to content
Go back

Implementing Row-Level Security (RLS) in PostgreSQL

Implementing Row-Level Security (RLS) in PostgreSQL

Introduction

Row-Level Security (RLS) restricts which rows are visible to a given database user, ideal for multi-tenant applications.

Prerequisites

Step 1: Enable RLS on Table

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

Step 2: Create Policy

CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.current_tenant')::int);

Step 3: Set Tenant Context

SET app.current_tenant TO '42';

Do this per session after user authentication.

Step 4: Insert Privilege Policy

CREATE POLICY tenant_insert ON orders
  FOR INSERT WITH CHECK (tenant_id = current_setting('app.current_tenant')::int);

Controls which rows can be inserted.

Step 5: Test RLS

SET app.current_tenant TO '1';
SELECT * FROM orders; -- sees only tenant 1 orders

Summary

PostgreSQL RLS enforces row-level permissions in the database, enhancing security for multi-tenant systems with minimal application changes.


Share this post on:

Previous Post
Using AWS S3 Signed URLs for Secure File Uploads
Next Post
Writing Complex Migrations with Drizzle ORM