Row Level Security
When you need granular authorization rules, nothing beats PostgreSQL's Row Level Security (RLS).
Policies are PostgreSQL's rule engine. They are incredibly powerful and flexible, allowing you to write complex SQL rules which fit your unique business needs.
Policies#
Policies are easy to understand once you get the hang of them. Each policy is attached to a table, and the policy is executed
every time a table is accessed.
You can just think of them as adding a WHERE
clause to every query. For example a policy like this ...
1create policy "Individuals can view their own todos."
2 on todos for select
3 using ( auth.uid() = user_id );
.. would translate to this whenever a user tries to select from the todos table:
1select *
2from todos
3where auth.uid() = todos.user_id; -- Policy is implicitly added.
Helper Functions#
Supabase provides you with a few easy functions that you can use with your policies.
auth.uid()
#
Returns the ID of the user making the request.
auth.jwt()
#
Returns the JWT of the user making the request.
Examples#
Here are some examples to show you the power of PostgreSQL's RLS.
Allow read access#
1-- 1. Create table 2create table profiles ( 3 id uuid references auth.users, 4 avatar_url text 5); 6 7-- 2. Enable RLS 8alter table profiles 9 enable row level security; 10 11-- 3. Create Policy 12create policy "Public profiles are viewable by everyone." 13 on profiles for select using ( 14 true 15 );
- Creates a table called
profiles
in the public schema (default schema). - Enables Row Level Security.
- Creates a policy which allows all
select
queries to run.
Restrict updates#
1-- 1. Create table
2create table profiles (
3 id uuid references auth.users,
4 avatar_url text
5);
6
7-- 2. Enable RLS
8alter table profiles
9 enable row level security;
10
11-- 3. Create Policy
12create policy "Users can update their own profiles."
13 on profiles for update using (
14 auth.uid() = id
15 );
- Creates a table called
profiles
in the public schema (default schema). - Enables RLS.
- Creates a policy which allows logged in users to update their own data.
Only anon or authenticated access#
You can add a Postgres role
1create policy "Public profiles are viewable by everyone." 2on profiles for select 3to authenticated, anon 4using ( 5 true 6);
Policies with joins#
Policies can even include table joins. This example shows how you can query "external" tables to build more advanced rules.
1create table teams (
2 id serial primary key,
3 name text
4);
5
6-- 2. Create many to many join
7create table members (
8 team_id bigint references teams,
9 user_id uuid references auth.users
10);
11
12-- 3. Enable RLS
13alter table teams
14 enable row level security;
15
16-- 4. Create Policy
17create policy "Team members can update team details if they belong to the team."
18 on teams
19 for update using (
20 auth.uid() in (
21 select user_id from members
22 where team_id = id
23 )
24 );
Note: If RLS is also enabled for members, the user must also have read (select) access to members. Otherwise the joined query will not yield any results.
Policies with security definer functions#
Policies can also make use of security definer functions
. This is useful in a many-to-many relationship where you want to restrict access to the linking table. Following the teams
and members
example from above, this example shows how you can use the security definer function in combination with a policy to control access to the members
table.
1-- 1. Follow example for 'Policies with joins' above
2
3-- 2. Enable RLS
4alter table members
5 enable row level security
6
7-- 3. Create security definer function
8create or replace function get_teams_for_authenticated_user()
9returns setof bigint
10language sql
11security definer
12set search_path = public
13stable
14as $$
15 select team_id
16 from members
17 where user_id = auth.uid()
18$$;
19
20-- 4. Create Policy
21create policy "Team members can update team members if they belong to the team."
22 on members
23 for all using (
24 team_id in (
25 select get_teams_for_authenticated_user()
26 )
27 );
Verifying email domains#
Postgres has a function right(string, n)
that returns the rightmost n characters of a string.
You could use this to match staff member's email domains.
1-- 1. Create table
2create table leaderboard (
3 id uuid references auth.users,
4 high_score bigint
5);
6
7-- 2. Enable RLS
8alter table leaderboard
9 enable row level security;
10
11-- 3. Create Policy
12create policy "Only Blizzard staff can update leaderboard"
13 on leaderboard
14 for update using (
15 right(auth.jwt() ->> 'email', 13) = '@blizzard.com'
16 );
Time to live for rows#
Policies can also be used to implement TTL or time to live feature that you see in Instagram stories or Snapchat.
In the following example, rows of stories
table are available only if they have been created within the last 24 hours.
1-- 1. Create table
2create table if not exists stories (
3 id uuid not null primary key DEFAULT uuid_generate_v4(),
4 created_at timestamp with time zone default timezone('utc' :: text, now()) not null,
5 content text not null
6);
7
8-- 2. Enable RLS
9alter table stories
10 enable row level security;
11
12-- 3. Create Policy
13create policy "Stories are live for a day"
14 on stories
15 for select using (
16 created_at > (current_timestamp - interval '1 day')
17 );
Advanced policies#
Use the full power of SQL to build extremely advanced rules.
In this example, we will create a posts
and comments
tables and then create a policy that depends on another policy.
(In this case, the comments policy depends on the posts policy.)
1create table posts (
2 id serial primary key,
3 creator_id uuid not null references auth.users(id),
4 title text not null,
5 body text not null,
6 publish_date date not null default now(),
7 audience uuid[] null -- many to many table omitted for brevity
8);
9
10create table comments (
11 id serial primary key,
12 post_id int not null references posts(id) on delete cascade,
13 user_id uuid not null references auth.users(id),
14 body text not null,
15 comment_date date not null default now()
16);
17
18create policy "Creator can see their own posts"
19on posts
20for select
21using (
22 auth.uid() = posts.creator_id
23);
24
25create policy "Logged in users can see the posts if they belong to the post 'audience'."
26on posts
27for select
28using (
29 auth.uid() = any (posts.audience)
30);
31
32create policy "Users can see all comments for posts they have access to."
33on comments
34for select
35using (
36 exists (
37 select 1 from posts
38 where posts.id = comments.post_id
39 )
40);
Tips#
Enable Realtime for database tables#
Realtime server broadcasts database changes to authorized users depending on your Row Level Security (RLS) policies. We recommend that you enable row level security and set row security policies on tables that you add to the publication. However, you may choose to disable RLS on a table and have changes broadcast to all connected clients.
1/** 2 * REALTIME SUBSCRIPTIONS 3 * Realtime enables listening to any table in your public schema. 4 */ 5 6begin; 7 -- remove the realtime publication 8 drop publication if exists supabase_realtime; 9 10 -- re-create the publication but don't enable it for any tables 11 create publication supabase_realtime; 12commit; 13 14-- add a table to the publication 15alter publication supabase_realtime add table products; 16 17-- add other tables to the publication 18alter publication supabase_realtime add table posts;
You don't have to use policies#
You can also put your authorization rules in your middleware, similar to how you would create security rules with any other backend <-> middleware <-> frontend
architecture.
Policies are a tool. In the case of "serverless/Jamstack" setups, they are especially effective because you don't have to deploy any middleware at all.
However, if you want to use another authorization method for your applications, that's also fine. Supabase is "just Postgres", so if your application works with Postgres, then it also works with Supabase.
Tip: Make sure to enable RLS for all your tables, so that your tables are inaccessible. Then use the "Service" which we provide, which is designed to bypass RLS.
Never use a service key on the client#
Supabase provides special "Service" keys, which can be used to bypass all RLS. These should never be used in the browser or exposed to customers, but they are useful for administrative tasks.
Deprecated features#
We have deprecate some functions to ensure better performance and extensibilty of RLS policies.
auth.role()
#
caution
Deprecated: The auth.role()
function has been deprecated in favour of using the TO
field, natively supported within Postgres.
1-- DEPRECATED
2create policy "Public profiles are viewable by everyone."
3on profiles for select using (
4 auth.role() = 'authenticated' or auth.role() = 'anon'
5);
6
7-- RECOMMENDED
8create policy "Public profiles are viewable by everyone."
9on profiles for select
10to authenticated, anon
11using (
12 true
13);
auth.email()
#
caution
Deprecated. Use auth.jwt() ->> 'email'
instead.
Returns the email of the user making the request.