Deutsch
GuideSupabase · Access control

Roles and permissions in Supabase: admins, members and viewers done right

How to build admin, member and viewer roles in Supabase that users can’t grant themselves: a roles table, app_metadata or a custom access token hook. Tested SQL.

By Tim GeithnerPublished 6 min read

Short answer

Store roles where users can’t write: a user_roles table that only your server changes, app_metadata set with the secret key, or a claim added by a custom access token hook. Check the role inside your RLS policies, for example with a security definer helper function. Never read a role from user_metadata: every signed-in user can edit it, so a role stored there lets anyone make themselves admin.

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • Never read a role from user_metadata. Every signed-in user can change it, and Supabase’s Security Advisor flags policies that do (lint 0015).
  • Watch for sign-up triggers that copy a role from raw_user_meta_data into a profile. That is the same hole one step later.
  • Three safe places for roles: a user_roles table only your server writes, app_metadata, or a claim from a custom access token hook.
  • Check roles in RLS policies. A hidden button is not a permission.
  • Token-based roles change only when the token is refreshed; a table lookup changes on the next query.

The hole: roles users can give themselves

Almost every app grows an admin area, and AI builders often reach for the most obvious place to store “this user is an admin”: the metadata the app already writes at sign-up. That produces one of two patterns.

The first reads the role from the token:

VulnerableA policy that trusts user_metadata
create policy "Admins can read all invoices"
  on public.invoices for select
  to authenticated
  using ((select auth.jwt() -> 'user_metadata' ->> 'role') = 'admin');

Supabase’s docs are direct about this: users can edit their own user metadata, so a role stored there lets a user grant themselves access. One call to supabase.auth.updateUser({ data: { role: "admin" } }) from the browser console, a token refresh, and the policy above lets that user read every invoice. In our test, a normal user saw one invoice with an honest token and all of them once their token said role: admin in user_metadata. The Security Advisor reports this as lint 0015, “security policy relies on user-editable data”.

The second pattern hides better. A trigger copies the role into a profiles table when the user signs up:

VulnerableA sign-up trigger that copies the role from metadata
create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  insert into public.profiles (id, role)
  values (new.id, coalesce(new.raw_user_meta_data ->> 'role', 'member'));
  return new;
end;
$$;

create trigger on_auth_user_created
  after insert on auth.users
  for each row execute function public.handle_new_user();

The policies then read profiles.role, which looks safe. But raw_user_meta_data is whatever the sign-up request sent, so anyone who calls signUp with options: { data: { role: "admin" } } starts life as an admin. In our test that is exactly what happened. Copy only harmless fields like a display name from metadata, and set roles somewhere else. This is improper privilege management (CWE-269 (opens in a new tab)).

Option 1: a roles table and a helper function

The most flexible approach is a table that maps users to roles, which only your server or the SQL Editor can write. This is close to what Supabase’s RBAC guide uses:

SafeRoles table and helper
create type public.app_role as enum ('viewer', 'member', 'admin');

create table public.user_roles (
  user_id uuid not null references auth.users (id) on delete cascade,
  role public.app_role not null,
  primary key (user_id, role)
);

alter table public.user_roles enable row level security;
revoke all on table public.user_roles from anon, authenticated;
grant select on table public.user_roles to authenticated;

create policy "Users can see their own roles"
  on public.user_roles for select
  to authenticated
  using ((select auth.uid()) = user_id);

create schema if not exists private;

create or replace function private.has_role_at_least(_min public.app_role)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
  select exists (
    select 1 from public.user_roles r
    where r.user_id = (select auth.uid())
      and r.role >= _min
  );
$$;

Why it is built this way:

  • The enum order is the hierarchy. Postgres compares enum values in the order they were declared, so 'admin' >= 'member' is true. One helper covers “at least a member”.
  • Users can read but not write their roles. The table grant allows only select, so an insert or update from the browser fails with permission denied before any policy runs. Supabase’s guide makes the same point: without that, any signed-in user could insert a row granting themselves admin.
  • The helper is security definer with search_path = '' in a schema the API doesn’t expose. It reads user_roles regardless of that table’s policies and can’t be called as an endpoint. Our guide on SECURITY DEFINER functions explains both settings.

Now the policies for a shared articles table: viewers read, members write their own, admins edit and delete everything.

SafePolicies by role
alter table public.articles enable row level security;

create policy "Viewers and up can read"
  on public.articles for select
  to authenticated
  using ((select private.has_role_at_least('viewer')));

create policy "Members can write their own articles"
  on public.articles for insert
  to authenticated
  with check (
    (select private.has_role_at_least('member'))
    and author_id = (select auth.uid())
  );

create policy "Members edit their own, admins edit all"
  on public.articles for update
  to authenticated
  using (
    ((select private.has_role_at_least('member')) and author_id = (select auth.uid()))
    or (select private.has_role_at_least('admin'))
  )
  with check (
    ((select private.has_role_at_least('member')) and author_id = (select auth.uid()))
    or (select private.has_role_at_least('admin'))
  );

create policy "Only admins delete"
  on public.articles for delete
  to authenticated
  using ((select private.has_role_at_least('admin')));

Wrapping the helper in select lets Postgres evaluate it once per query instead of once per row. To make someone an admin, run this in the SQL Editor or from server code with the secret key:

Grant a role (server or SQL Editor only)
insert into public.user_roles (user_id, role)
values ('11111111-1111-1111-1111-111111111111', 'admin');

For roles per workspace (admin of team A, viewer in team B), add a workspace_id column to user_roles and pass it to the helper. The multi-tenant data isolation guide covers that variant.

Option 2: app_metadata

If you only need a single role per user and don’t want a table, store it in app_metadata. Supabase’s docs say users can’t change it themselves; you set it from a trusted server with the secret key:

Edge Function or backend (sketch)
// Secret key, server side only.
await supabaseAdmin.auth.admin.updateUserById(userId, {
  app_metadata: { role: "admin" },
});

The policy reads it from the token:

SafeA policy that trusts app_metadata
create policy "Admins can read all invoices"
  on public.invoices for select
  to authenticated
  using ((select auth.jwt() -> 'app_metadata' ->> 'role') = 'admin');

It differs from the bad example above by one word, and that word decides who can write the value. The trade-off: the role is part of the access token, so a promotion or demotion only takes effect once the user’s token is refreshed. Supabase’s RLS guide notes that a JWT is not always up-to-date.

Option 3: a custom access token hook

Supabase’s RBAC guide combines both: roles live in user_roles, and a Postgres function adds them to every new token as a claim. Here is a compact version that adds the user’s highest role:

SafeCustom access token hook
create or replace function public.custom_access_token_hook(event jsonb)
returns jsonb
language plpgsql
stable
as $$
declare
  claims jsonb := event -> 'claims';
  top_role public.app_role;
begin
  select max(role) into top_role
  from public.user_roles
  where user_id = (event ->> 'user_id')::uuid;

  claims := jsonb_set(claims, '{user_role}', coalesce(to_jsonb(top_role), 'null'::jsonb));
  return jsonb_set(event, '{claims}', claims);
end;
$$;

grant usage on schema public to supabase_auth_admin;
grant execute on function public.custom_access_token_hook to supabase_auth_admin;
revoke execute on function public.custom_access_token_hook from authenticated, anon, public;
grant select on table public.user_roles to supabase_auth_admin;

create policy "Auth admin can read roles"
  on public.user_roles for select
  to supabase_auth_admin
  using (true);

Then enable it under Authentication → Hooks and use the claim in policies:

A policy on the hook's claim
create policy "Admins can delete any comment"
  on public.comments for delete
  to authenticated
  using ((select auth.jwt() ->> 'user_role') = 'admin');

The grants matter: only supabase_auth_admin, the role Supabase Auth uses, may run the hook. In our test, calling it as a signed-in user or a visitor failed with permission denied for function. Like option 2, the claim is only as fresh as the token.

How do you test roles?

Use one test user per role, plus one without any role, and run every action as each of them. The technique is the same as in our guide on testing RLS policies: switch to the authenticated role inside a transaction, set the user’s ID, try the action, roll back. For the articles policies above, the expected results are:

  • no role: reads nothing, writes nothing,
  • viewer: reads everything, every insert fails,
  • member: reads everything, creates and edits only rows with their own author_id, deletes nothing,
  • admin: edits and deletes every row.

Add one more check that is easy to forget: a member tries to insert into user_roles. It must fail. If it doesn’t, every other check is meaningless.

Which option should you pick?

Roles table + helperapp_metadataAccess token hook
Who writes the roleyour server / SQLyour server (secret key)your server / SQL
Change takes effectnext querynext token refreshnext token refresh
Several roles or per workspaceyesawkwardyes
Cost per queryone indexed lookupnonenone
Frontend can read itselect own rowfrom the sessiondecode the access token

For most AI-built SaaS apps, the roles table is the easiest to get right and to audit. Whatever you choose, keep showing or hiding admin buttons in the frontend for convenience, and enforce the rule in the database. The fix for an admin check that only lives in the frontend shows what goes wrong otherwise.

A fix prompt for your AI builder

Move roles out of user_metadata

Find every place in this project that reads a user’s role or permissions: RLS policies, database functions, triggers on auth.users, Edge Functions and frontend code. List each one and say whether it reads user_metadata, raw_user_meta_data, app_metadata, a table or a JWT claim.

Then add a migration that creates an enum app_role (‘viewer’, ‘member’, ‘admin’), a table public.user_roles (user_id, role, primary key on both) with RLS enabled, all privileges revoked from anon and authenticated, select granted to authenticated and a policy that lets users read only their own rows. Add a security definer function private.has_role_at_least(_min app_role) with set search_path = ‘’ that checks the current user’s roles. Rewrite every policy that used user_metadata to use this function. Change any sign-up trigger so it never copies a role from raw_user_meta_data.

Do not create any insert, update or delete policy on user_roles. Show me the migration and the list before applying anything.

Frequently asked questions

Can I store a user’s role in user_metadata?

Not for anything that grants access. Supabase’s docs say users can edit their own user metadata, so a role stored there lets a user give themselves that role. Use app_metadata, a roles table or a custom access token hook instead.

What is the difference between app_metadata and user_metadata?

Both are stored on auth.users and copied into the user’s token. user_metadata (raw_user_meta_data) can be changed by the signed-in user. app_metadata (raw_app_meta_data) can’t; you set it from a trusted server with the secret key.

Why doesn’t a role change take effect immediately?

If the role comes from the token (app_metadata or an access token hook), the user keeps the old value until their access token is refreshed. A roles table that your policies read directly takes effect on the next query.

Is hiding the admin button in the frontend enough?

No. Hiding buttons is good UX, but anyone can call your API directly with the public key. The real check has to be in the database policy or in server code.

Sources

  1. 1.Custom Claims & Role-based Access Control (RBAC) — Supabase Docs
  2. 2.Custom Access Token Hook — Supabase Docs
  3. 3.User management: user data — Supabase Docs
  4. 4.Row Level Security — Supabase Docs
  5. 5.Performance and Security Advisors (lint 0015) — Supabase Docs
  6. 6.CWE-269: Improper Privilege Management — MITRE

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt