Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 31 ยท Authentication

Users, Roles and Custom Claims

Store profile data safely, give users roles with Firebase custom claims or Supabase app_metadata, create profile triggers, and link accounts.

Authentication tells you who a user is. Most apps also need to know what they may do (admin, editor, customer) and to keep extra facts about them (display name, avatar, plan). Both platforms keep the auth user in a protected system area that you cannot freely extend, so the usual design is: a small, trusted set of claims for roles, and a normal table or collection for the profile.

This lesson shows the real code for both platforms (read-only) and a runnable stand-in that checks roles on decoded claims. It follows OAuth Providers, Magic Links and JWTs, where tokens and claims were introduced.

Auth user versus profile

The auth user holds identity: ID, email, providers, last sign-in. It is managed by the auth service, so you do not write your own fields into it directly from the client. Your app data about the user lives elsewhere.

Two places for user data

Auth user ID, email, providers. Managed by the service.
Profile Name, avatar, settings. Your own table or collection.
Claims Small trusted facts like role. Set only by servers.

Roles go in claims. Everything else goes in the profile.

1 / 2

In Firestore the convention is a document at users/{uid}. In Supabase it is a profiles table whose id references auth.users(id). Because the auth tables live in a schema your client cannot query directly, the profile table is also what lets you show other users' names.

Supabase: profile table and trigger

A trigger is a database function that runs automatically on an event. The standard pattern creates a profile row whenever someone signs up. This SQL is read-only because it needs a Supabase project (the auth schema does not exist in the browser SQLite runner).

SQL
-- Supabase SQL (read-only)
create table public.profiles (
  id uuid primary key references auth.users (id) on delete cascade,
  display_name text,
  avatar_url text,
  created_at timestamptz not null default now()
);

alter table public.profiles enable row level security;

create function public.handle_new_user()
returns trigger
language plpgsql
security definer set search_path = ''
as $$
begin
  insert into public.profiles (id, display_name)
  values (new.id, new.raw_user_meta_data ->> 'display_name');
  return new;
end;
$$;

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

security definer makes the function run with its owner's rights so it can write the profile, and set search_path = '' is a safety habit. Policies that let each user edit only their own row come in Row Level Security Policies.

Supabase gives each user two metadata fields, and the difference is important:

  • user_metadata (raw_user_meta_data) can be changed by the user through supabase.auth.updateUser({ data: { ... } }). Treat it like any user input.
  • app_metadata (raw_app_meta_data) can be changed only with the service role key, on a server. Use it for roles.
JavaScript
// Supabase admin call on a SERVER with the service role key (read-only)
const { error } = await supabaseAdmin.auth.admin.updateUserById(userId, {
  app_metadata: { role: "editor" },
});

The role appears inside the user's JWT after the next token refresh, in app_metadata.role. In SQL, policies can read it with auth.jwt() -> 'app_metadata' ->> 'role'.

Do not base permissions on user_metadata. A user can set it to anything, including { "role": "admin" }. Only app_metadata (or a server-side table) is safe for roles.

Firebase: custom claims

Firebase lets a trusted server attach small custom claims to a user with the Admin SDK. They are added to the user's ID token.

JavaScript
// Node.js with firebase-admin (read-only)
import { getAuth } from "firebase-admin/auth";

await getAuth().setCustomUserClaims(uid, { role: "editor", orgId: "acme" });

On the client, claims show up only after the token is refreshed:

JavaScript
// Browser (read-only)
await auth.currentUser.getIdToken(true);               // force refresh
const { claims } = await auth.currentUser.getIdTokenResult();
console.log(claims.role);                              // "editor"

In security rules the same claims are available as request.auth.token.role. Claims are limited to about 1000 bytes in total, so store a role or a few IDs, never lists of data. See Firestore Security Rules.

Roles: admin and normal users

Keep role design simple and explicit.

  1. Decide a short list of roles (user, editor, admin) and what each may do.
  2. Let only trusted server code assign them: a Cloud Function or an Edge Function that first checks the caller is an admin.
  3. Check the role in every place that matters: rules or policies, and server functions. Hiding a button in the UI is convenience, not security.
  4. Remember the delay: a changed role takes effect after the user's token refreshes (up to an hour by default, or immediately if you force a refresh).

Bootstrapping the first admin is a one-time manual step using the Admin SDK or the Supabase dashboard's SQL editor.

Stand-in: a role check on decoded claims

The code below stands in for a rule or policy: it reads claims from a decoded token and decides allow or deny. It also rejects roles found in the user-editable metadata, mirroring the Supabase warning above.

JS Stand-in: role checks on decoded claims

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sneaky user wrote role: "admin" into user_metadata, yet can still treats them as a plain user, because roleOf ignores that field. Anonymous visitors (no token) default to the lowest rank, and unknown actions are denied. Denying by default is the safe habit.

A second stand-in shows the refresh delay: a role change on the server is not visible in a token that was issued earlier.

JS Stand-in: stale claims until the token refreshes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is why Firebase offers getIdToken(true) and why role changes in Supabase appear at the next refresh. For revoking access quickly, keep the role in a table that rules check on every request, at the price of one extra read or query.

Linking accounts

A person might sign up with an email password and later click "Continue with Google". Without linking, they end up with two separate users.

  • Firebase supports linking explicitly: linkWithCredential(auth.currentUser, credential) or linkWithPopup. By default, one email can map to one account, and an attempt to sign in with a second provider for the same email raises auth/account-exists-with-different-credential, which your app handles by asking the user to sign in with the first method and then link.
  • Supabase can link identities when the emails match and are verified (automatic linking), and offers supabase.auth.linkIdentity({ provider: "github" }) for a signed-in user. Check your project's settings, since linking an unverified email would let someone take over an account.

The danger to remember: linking by an unverified email is an account takeover risk. Only link when the email is verified by the provider.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a Supabase user's role be stored so the user cannot change it?

    user_metadata is writable by the user. app_metadata can only be changed by trusted server code.
  2. 2. How does a Firebase custom claim reach the client?

    Claims are part of the ID token. The client sees a new claim after refreshing the token.
  3. 3. What is a profile trigger in Supabase for?

    An after-insert trigger on auth.users can insert the matching row into public.profiles.
  4. 4. Hiding the admin button in the UI is enough to protect admin actions. True or false?

    Clients can call the API directly, so enforcement must live where the data is.

Summary

  • The auth user holds identity; keep profile data in your own table (profiles) or collection (users/{uid}).
  • Roles are small trusted claims: Firebase custom claims set with the Admin SDK, Supabase app_metadata set with the service role key.
  • Never trust user_metadata for permissions; the user controls it.
  • Changed claims appear after the token refreshes, so force a refresh or keep roles in a table when you need instant effect.
  • Link accounts only through verified emails, and enforce roles where the data lives.

Next: Firestore Data Model