Supabase Row Level Security Policies

Lock down Supabase tables with row level security policies keyed to auth claims, scoping reads and writes to tenant ownership.

TypescriptSecurity Boundaries

Code

typescriptsnippet
20 lines
-- Supabase RLS policies:run at the Postgres layer
alter table projects enable row level security;

create policy "tenant read own projects"
  on projects for select
  using (tenant_id = auth.jwt() ->> 'tenant_id');

create policy "tenant insert own projects"
  on projects for insert
  with check (tenant_id = auth.jwt() ->> 'tenant_id');

create policy "tenant update own projects"
  on projects for update
  using (tenant_id = auth.jwt() ->> 'tenant_id')
  with check (tenant_id = auth.jwt() ->> 'tenant_id');

-- 服务端绕行角色仅在维护任务中使用
create policy "service role full access"
  on projects for all
  using (auth.role() = 'service_role');

What the code does

The SQL script first flips RLS on with alter table projects enable row level security;, then declares four policies on projects. The select policy uses using (tenant_id = auth.jwt() ->> 'tenant_id') so rows are only visible when their tenant_id matches the JWT claim; the insert policy enforces the same comparison through with check; the update policy pairs using and with check so a row must both match the filter and pass the write check. The final for all policy grants the service_role full access via auth.role() = 'service_role', reserved for maintenance tasks.

Core lines

with check (tenant_id = auth.jwt() ->> 'tenant_id');
alter table projects enable row level security;
using (tenant_id = auth.jwt() ->> 'tenant_id');

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used.