new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Supabase · all subjects

auth/custom-claims-and-rbac

29 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Server-side JWT packages

For server-side JWT decoding and validation, use packages like express-jwt, koa-jwt, PyJWT, dart_jsonwebtoken, or Microsoft.AspNetCore.Authentication.JwtBearer depending on your tech stack.

Custom Claims definition and purpose

Custom Claims are special attributes attached to a user that can be used to control access to portions of an application. Examples include user_role, plan, user_level, group_name, joined_on, group_manager, and items array.

RBAC implementation with Custom Access Token Auth Hook

To implement Role-Based Access Control (RBAC) with custom claims, use a Custom Access Token Auth Hook. This hook runs before a token is issued and allows you to add additional claims to the user's JWT.

Custom types for app_permission and app_role

Create two custom enum types in PostgreSQL: app_permission as enum with values ('channels.delete', 'messages.delete'), and app_role as enum with values ('admin', 'moderator').

user_roles table schema

The user_roles table has: id (bigint generated by default as identity primary key), user_id (uuid references auth.users on delete cascade, not null), role (app_role, not null), with a unique constraint on (user_id, role). It stores application roles for each user.

role_permissions table schema

The role_permissions table has: id (bigint generated by default as identity primary key), role (app_role, not null), permission (app_permission, not null), with a unique constraint on (role, permission). It stores application permissions for each role.

Example role permissions setup

Insert role and permission mappings: admin role gets both 'channels.delete' and 'messages.delete' permissions, while moderator role gets only 'messages.delete' permission.

Custom access token hook function implementation

The custom_access_token_hook function in PL/pgSQL: takes event jsonb as parameter, fetches the user's role from public.user_roles table by user_id, sets the user_role claim in the JWT using jsonb_set on event->>'claims', and returns the modified event. Function is stable and language plpgsql.

Auth hook grants and permissions

Grant usage on schema public to supabase_auth_admin. Grant execute on custom_access_token_hook to supabase_auth_admin only. Revoke execute from authenticated, anon, and public. Grant all on user_roles table to supabase_auth_admin. Revoke all from authenticated, anon, public. Create permissive select policy on user_roles for supabase_auth_admin allowing read access.

Enable auth hook in dashboard

To enable the auth hook, navigate to Authentication > Hooks (Beta) in the dashboard and select the appropriate Postgres function from the dropdown menu. For local development, follow the local development instructions in Auth Hooks documentation.

authorize function for RLS policies

Create a function public.authorize(requested_permission app_permission) that returns boolean. It fetches the user's role from auth.jwt() ->>'user_role', casts it to app_role, counts matching permissions in role_permissions table where role and permission match, and returns true if count > 0. Function is language plpgsql, stable, security definer with search_path set to empty string.

Using authorize in RLS delete policies

Use the authorize function in RLS policies for delete access. Example: create policy "Allow authorized delete access" on public.channels for delete to authenticated using ((SELECT authorize('channels.delete'))); and similar for public.messages with 'messages.delete' permission.

Accessing custom claims in JavaScript client

Use the jwt-decode package to decode the access_token JWT. Subscribe to auth state changes with supabase.auth.onAuthStateChange(), then decode session.access_token and access properties like jwt.user_role. Example: const jwt = jwtDecode(session.access_token); const userRole = jwt.user_role;

Auth hook only modifies access token JWT

The auth hook only modifies the access token JWT, not the auth response. To access custom claims in your application (browser client or server-side middleware), you must decode the access_token JWT from the auth session.

Disable link tracking with custom SMTP to preserve auth links

When using a custom SMTP service, some services might have link tracking enabled which may overwrite or deform the email confirmation links sent by Supabase Auth. Disable link tracking when using a custom SMTP service to prevent this.

Enable row level security on all tables before production

Ensure row level security (RLS) is enabled on all tables from the Database > Tables section of the Supabase Dashboard. Tables without RLS enabled with reasonable policies allow any client to access and modify their data. This is a critical security requirement before going to production.

Enable email confirmations in authentication

Enable email confirmations in the Authentication > Providers section of the dashboard.

Set reasonable OTP expiry time

Set the expiry in the Authentication > Providers section of the dashboard for one-time passwords (OTPs) to a reasonable value. The recommendation is to set this to 3600 seconds (1 hour) or lower. Increase the length of the OTP if you need a higher level of entropy.

Use custom SMTP server for auth emails

Use a custom SMTP server for auth emails so that users can see that the mails are coming from a trusted domain, preferably the same domain that your app is hosted on. Grab SMTP credentials from major email providers such as SendGrid, AWS SES, etc.

Set up MFA for users if high security required

If your application requires a higher level of security, consider setting up multi-factor authentication (MFA) for your users.

Use own SMTP credentials for auth emails in production

Use your own SMTP credentials in the Authentication > Emails > SMTP Settings section of the dashboard so that you have full control over the deliverability of your transactional auth emails. You can grab SMTP credentials from major email providers such as SendGrid, AWS SES, etc.

Custom SMTP rate limit for auth emails

The default rate limit for auth emails when using a custom SMTP provider is 30 new users per hour. If you are doing a major public announcement, you will likely require more than this.

Auth rate limits table

Authentication rate limit quotas: | Endpoint | Path | Limited By | Rate Limit | |----------|------|------------|------------| | All endpoints that send emails | `/auth/v1/signup` `/auth/v1/recover` `/auth/v1/user` | Sum of combined requests | As of 3 Sep 2024, emails per hour (configurable with custom SMTP setup) | | All endpoints that send OTPs | `/auth/v1/otp` | Sum of combined requests | Defaults to 360 OTPs per hour. Is customizable | | Send OTPs or magic links | `/auth/v1/otp` | Last request | Defaults to 60 seconds window before a new request is allowed. Is customizable | | Signup confirmation request | `/auth/v1/signup` | Last request | Defaults to 60 seconds window before a new request is allowed. Is customizable | | Password Reset Request | `/auth/v1/recover` | Last request | Defaults to 60 seconds window before a new request is allowed. Is customizable | | Verification requests | `/auth/v1/verify` | IP Address | 360 requests per hour (with bursts up to 30 requests) | | Token refresh requests | `/auth/v1/token` | IP Address | 1800 requests per hour (with bursts up to 30 requests) | | Create or Verify an MFA challenge | `/auth/v1/factors/:id/challenge` `/auth/v1/factors/:id/verify` | IP Address | 15 requests per minute (with bursts up to 30 requests) | | Anonymous sign-ins | `/auth/v1/signup` | IP Address | 30 requests per hour (with bursts up to 30 requests) | Rate limits are configurable in the Authentication > Rate Limits section of the dashboard.

Configure auth rate limits in dashboard

Configure authentication rate limits for your project in the Authentication > Rate Limits section of the dashboard.

Use CAPTCHA protection against auth abuse

Supabase provides CAPTCHA protection on the signup, sign-in and password reset endpoints. Read the Auth CAPTCHA guide for more details on how to protect against abuse using this method.

Email scanner issue with single-use magic links

When working with enterprise systems, email scanners may scan and make a GET request to the reset password link or sign-up link in your email. Since links in Supabase Auth are single-use, a user who opens an email post-scan to click on a link will receive an error. To work around this, consider altering the email template to replace the original magic link with a link to a domain you control. The domain can present the user with a Sign-in button, which redirects the user to the original magic link URL when clicked.

GoTrue provides JWT-based authentication

GoTrue is a JWT-based API for managing users and issuing access tokens. It integrates with Postgres Row Level Security and the API servers. The source code is at github.com/supabase/gotrue, written in Go, and licensed under MIT.

Authorization via Row Level Security and Postgres Policies

Control the data each user can access with Postgres Policies through Row Level Security. This feature is generally available and fully available on self-hosted deployments.

Row level security (RLS) policies definition

Row level security policies are special objects within the Postgres database that limit the available operations or data returned to clients. RLS policies use information contained in a JWT to identify users and the actions and data they are allowed to perform or view.

Give your agent this brain