row-level security policies in Supabase for a multitenant application #149922
-
Select Topic AreaQuestion BodyI’m having a really hard time setting up RLS policies in Supabase. I’m building a multi-tenant app, and I need to restrict access to rows based on the CREATE POLICY "Tenant can access their own data"
ON my_table
FOR SELECT
USING (tenant_id = auth.uid()); But when I query the table, I’m still seeing all the rows, not just the ones for the current tenant. Am I missing something? Any help would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
No need to worry, RLS can be a bit tricky at first, but I’ll walk you through it... :D First, it looks like you’re on the right track with your policy, but there’s a small misunderstanding. The Here’s an example of how you can set this up:
CREATE POLICY "Tenant can access their own data"
ON my_table
FOR SELECT
USING (
tenant_id = (
SELECT tenant_id
FROM profiles
WHERE user_id = auth.uid()
)
);
CREATE POLICY "Tenant can access their own data"
ON my_table
FOR SELECT
USING (
tenant_id = (auth.jwt() ->> 'tenant_id')::uuid
); Make sure your JWT includes the
ALTER TABLE my_table ENABLE ROW LEVEL SECURITY; Finally, test your setup by querying the table while authenticated as a user with a specific |
Beta Was this translation helpful? Give feedback.
No need to worry, RLS can be a bit tricky at first, but I’ll walk you through it... :D
First, it looks like you’re on the right track with your policy, but there’s a small misunderstanding. The
auth.uid()
function returns the UUID of the currently authenticated user, not thetenant_id
. If yourtenant_id
is stored in a different way (e.g., in aprofiles
table or as a custom claim in the JWT), you’ll need to adjust your policy accordingly.Here’s an example of how you can set this up:
profiles
table that stores thetenant_id
for each user. You can create a policy that joins theprofiles
table to enforce the restriction: