Skip to content

Updated

Restrict anonymous user access

Restrict what anonymous users can do in your database by telling them apart from permanent users in row-level security (RLS) policies.

Check the claim

An anonymous user uses the authenticated role, like a permanent user. To tell them apart in row-level security (RLS) policies, check the is_anonymous claim in the JWT that auth.jwt() returns.

Run the following SQL using the SQL Editor in the Supabase Dashboard or with psql over a direct connection. To connect with psql, see Direct connection.

create policy "Only permanent users can post to the news feed"
on news_feed as restrictive for insert
to authenticated
with check ((select (auth.jwt()->>'is_anonymous')::boolean) is false );
create policy "Permanent users can post to the news feed"
on news_feed for insert
to authenticated
with check ( true );
create policy "Anonymous and permanent users can view the news feed"
on news_feed for select
to authenticated
using ( true );

Check the current state instead

To check the current state, read is_anonymous from auth.users through a security definer function. Create the function in a schema the Data API doesn't expose, such as private, and set search_path = ''.

Run the following SQL using the SQL Editor in the Supabase Dashboard or with psql over a direct connection. To connect with psql, see Direct connection.

create schema if not exists private;
create function private.is_permanent_user()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from auth.users
where id = (select auth.uid()) and is_anonymous is false
);
$$;
revoke all on function private.is_permanent_user() from public;
grant usage on schema private to authenticated;
grant execute on function private.is_permanent_user() to authenticated;
alter policy "Only permanent users can post to the news feed"
on news_feed
with check ( (select private.is_permanent_user()) );

The alter policy statement replaces the claim check in the policy from the previous example, so stale tokens no longer fail. For a fresh setup, create the policy with create policy ... as restrictive for insert and the same with check expression, and add the permissive insert policy from the previous example.

Next steps

To keep going, use these pages: