w3resource

A Guide to PostgreSQL Row-Level Security


PostgreSQL: Implementing Row-Level Security (RLS)

PostgreSQL's Row-Level Security (RLS) is a powerful feature that enables fine-grained access control by restricting rows based on user roles, attributes, or other conditions. This feature is useful in multi-tenant applications or when managing sensitive data.

1. Enabling Row-Level Security

To enable RLS on a table, you first need to activate the security policy feature:

ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;

2. Creating Policies

RLS policies define which rows users can interact with. Policies can be applied to SELECT, INSERT, UPDATE, or DELETE operations.

Example: Restrict Access by User

Suppose you have a users table with a column owner_id representing the user who owns the data:

a. Create a policy to allow users to access only their rows:

Code:

CREATE POLICY user_row_access_policy
ON users
USING (owner_id = current_user);

b. To enable this policy, execute:

Code:

ALTER TABLE users FORCE ROW LEVEL SECURITY;

3. Policy Types

Policy Type Description Example
USING Defines the condition for SELECT queries. USING (owner_id = current_user)
WITH CHECK Defines the condition for INSERT/UPDATE. WITH CHECK (owner_id = current_user)

4. Testing RLS

To test the applied policies:

a. Switch User:

SET ROLE user_name;

b. Run Queries:

Execute queries to ensure the policy is applied correctly.

5. Disabling RLS

If you want to temporarily disable RLS for debugging or specific use cases:

6. Use Cases for RLS

Scenario RLS Use Case
Multi-tenant applications Isolate tenant data based on tenant ID.
Data privacy Restrict access to rows containing sensitive data.
Role-based access control Allow only admins to view all data.

Additional Notes:

  • Performance Impact: Properly define indexes to mitigate performance issues with RLS.
  • Audit Policies: Ensure your policies align with security and compliance requirements.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-row-level-security.php