Using authentication policies with views #901
-
It appears that row-level policies set in the dashboard don't apply to views. Let's say I have the following table and view in Supabase. CREATE TABLE posts (
id uuid primary key,
title varchar(100),
author uuid not null,
);
CREATE VIEW sorted_titles as SELECT title FROM posts ORDER BY title; Now I only want users to be able to read their own posts. So I added a policy to the Authentication > Policies tab in the Supabase dashboard for SELECT on "posts". auth.uid() = author Great! Now if a user tries to access posts in the table, they'll only get their own posts. However, this query will now returns everyone's posts, not just a user's own post. supabase.from('sorted_titles').select('*') Is there a way to still use the row level policies with the view? P.S. Sorry if this is common knowledge in postgres, I'm learning postgres at the same time I'm exploring Supabase. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 16 replies
-
Edit: For PostgreSQL 15, this now is supported natively with security invoker views: CREATE VIEW sorted_titles WITH (security_invoker) as SELECT title FROM posts ORDER BY title; Edit: The below answer is for projects with PostgreSQL <= 14
Yes, this is a quirk of how views work. They're called with the privileges of the role that created them(the owner). If you did To fix this you can change the view's owner with: ALTER VIEW sorted_titles OWNER TO authenticated; Then the view will respect the RLS policies you've defined. |
Beta Was this translation helpful? Give feedback.
-
Hello, any news on when we can expect Supabase instances to be upgraded to Postgres 15 to get the security invoker feature on views? |
Beta Was this translation helpful? Give feedback.
-
Hi, after some digging about this topic (views and RLS on them) i ended up with two main concepts:
But i have problems to understand one think: For example if i have a table with a RLS policy that enable only the owner to view his rows and i have a view (with fewer columns redacted from the table) and i want to show them ONLY to the authenticated group or only a set of users (private subscribers maybe like instagram), how can i achieve this? TL;DR: How can i apply different RLS policies to the table and the views separately? Thanks you all for the support❤️ |
Beta Was this translation helpful? Give feedback.
Edit: For PostgreSQL 15, this now is supported natively with security invoker views:
Edit: The below answer is for projects with PostgreSQL <= 14
Yes, this is a quirk of how views work. They're called with the privileges of the role that created them(the owner). If you did
CREATE VIEW
through the SQL Editor, then the owner issupabase_admin
and that role is a SUPERUSER(it bypasses RLS).To fix this you can change the view's owner with: