Auth

Auth Hooks

Supabase allows you to use Postgres functions to alter the default Supabase Auth flow. Developers can use hooks to add custom behavior that's not supported natively.

Hooks help you:

  • Track the origin of user signups by adding metadata
  • Improve security by adding additional checks to password and multi-factor authentication
  • Support legacy systems by integrating with identity credentials from external authentication systems
  • Add additional custom claims to your JWT

You can use hooks at specific points along an Auth flow to perform custom behavior via Postgres Functions. The following hooks are available:

HookAvailable on Plan
Custom Access TokenFree, Pro
MFA Verification AttemptTeams and Enterprise
Password Verification AttemptTeams and Enterprise

You can connect a hook to Supabase Auth to signal to Supabase Auth that it should make use of the hook.

Create a hook

What is a hook

A hook is a Postgres Function with a single argument -- the event of type JSONB -- and which returns a JSONB object.

This function is invoked by Supabase Auth at its point in the flow by providing an event object. The object returned by the function gives instructions on how Supabase Auth should continue processing.

To access properties of the event argument, you can use the JSON operators and functions.

There are no restrictions as to what language can be used to write Auth Hooks. If PL/pgSQL is too difficult consider using the plv8 extension which lets you use JavaScript to define functions.

Here is an example hook signature:


_11
create or replace function public.custom_access_token_hook(event jsonb)
_11
returns jsonb
_11
language plpgsql
_11
as $$
_11
declare
_11
-- Insert variables here
_11
begin
_11
-- Insert logic here
_11
return event;
_11
end;
_11
$$;

You can visit SQL Editor > Templates for hook templates.

Hook grants and roles

You need to assign additional permissions so that Supabase Auth can access the hook as well as the tables it interacts with.

The supabase_auth_admin role does not have permissions to the public schema. You need to grant the role permission to execute your hook function:


_10
grant execute
_10
on function public.custom_access_token_hook
_10
to supabase_auth_admin;

You also need to grant usage to supabase_auth_admin:


_10
grant usage on schema public to supabase_auth_admin;

Also revoke permissions from the authenticated and anon roles to ensure the function is not accessible by Supabase Serverless APIs.


_10
revoke execute
_10
on function public.custom_access_token_hook
_10
from authenticated, anon;

For security, we recommend against the use the security definer tag. The security definer tag specifies that the function is to be executed with the privileges of the user that owns it. When a function is created via the Supabase dashboard with the tag, it will have the extensive permissions of the postgres role which make it easier for undesirable actions to occur.

We recommend that you do not use any tag and explicitly grant permissions to supabase_auth_admin as described above.

Read more about security definer tag in our database guide.

Hook errors

You should return an error when facing a runtime error. Runtime errors are specific to your application and arise from specific business rules rather than programmer errors.

Runtime errors could happen when:

  • The user does not have appropriate permissions
  • The event payload received does not have required claims.
  • The user has performed an action which violates a business rule.

The error is a JSON object and has the following properties:

  • error An object that contains information about the error.
    • http_code A number indicating the HTTP code to be returned. If not set, the code is HTTP 500 Internal Server Error.
    • message A message to be returned in the HTTP response. Required.

Here's an example:


_10
{
_10
"error": {
_10
"http_code": 429,
_10
"message": "You can only verify a factor once every 10 seconds."
_10
}
_10
}

When an error is returned, the error is propagated from the hook to Supabase Auth and translated into a HTTP error which is returned to your application. Supabase Auth will only take into account the error and disregard the rest of the payload.

Timeouts

Ensure that your hooks complete within 2 seconds to avoid any errors.

Connect a hook

In the dashboard, navigate to Authentication > Hooks (Beta) and select the appropriate PostgreSQL function from the dropdown menu.

Hook: MFA verification attempt

You can add additional checks to the Supabase MFA implementation with hooks. For example, you can:

  • Limit the number of verification attempts performed over a period of time.
  • Sign out users who have too many invalid verification attempts.
  • Count, rate limit, or ban sign-ins.

Inputs

Supabase Auth will supply the following fields to your hook:

  • factor_id Unique identifier for the MFA factor being verified.
  • user_id Unique identifier for the user.
  • valid Whether the verification attempt was valid. For TOTP, this means that the six digit code was correct (true) or incorrect (false).

Example payload:


_10
{
_10
"factor_id": "6eab6a69-7766-48bf-95d8-bd8f606894db",
_10
"user_id": "3919cb6e-4215-4478-a960-6d3454326cec",
_10
"valid": true
_10
}

Outputs

Return this if your hook processed the input without errors.

  • decision A string containing the decision on whether to allow authentication to move forward. Use reject to deny the verification attempt and log the user out of all active sessions. Use continue to use the default Supabase Auth behavior.
  • message The message to show the user if the decision was reject.

Example output:


_10
{
_10
"decision": "reject",
_10
"message": "You have exceeded maximum number of MFA attempts."
_10
}

Examples

Hook: Password verification attempt

Your company wishes to increase security beyond the requirements of the default password implementation in order to fulfill security or compliance requirements. You plan to track the status of a password sign-in attempt and take action via an email or a restriction on logins where necessary.

As this hook runs on unauthenticated requests, malicious users can abuse the hook by calling it multiple times. Pay extra care when using the hook as you can unintentionally block legitimate users from accessing your application.

Check if a password is valid prior to taking any additional action to ensure the user is legitimate. Where possible, send an email or notification instead of blocking the user.

Inputs

  • user_id Unique identifier for the user attempting to sign in. Correlate this to the auth.users table.
  • valid Whether the password verification attempt was valid.

_10
{
_10
"user_id": "3919cb6e-4215-4478-a960-6d3454326cec",
_10
"valid": true
_10
}

Outputs

Return these only if your hook processed the input without errors.

  • decision A string containing the decision whether to allow authentication to move forward. Use reject to completely reject the verification attempt and log the user out of all active sessions. Use continue to use the default Supabase Auth behavior.
  • message The message to show the user if the decision was reject.
  • should_logout_user Whether to logout a user if a reject decision is issued. Has no effect when a continue decision is issued.

Example output:


_10
{
_10
"decision": "reject",
_10
"message": "You have exceeded maximum number of password sign-in attempts.",
_10
"should_logout_user": "false"
_10
}

Examples

Hook: Custom access token

The custom access token hook runs before a token is issued and allows you to add additional claims based on the authentication method used.

Claims returned must conform to our specification. Supabase Auth will check for these claims after the hook is run and return an error if they are not present.

These are the fields currently available on an access token:

Required Claims: aud, exp, iat, sub, email, phone, role, aal, session_id Optional Claims: jti, iss, nbf, app_metadata, user_metadata, amr

Inputs

  • user_id Unique identifier for the user attempting to sign in. Correlate this to the auth.users table.
  • claims Claims which are attached to the access token.
  • authentication_method the authentication method used to request the access token. Possible values include: oauth, password, otp, totp, recovery, invite, sso/saml, magiclink, email/signup, email_change, token_refresh.

Outputs

Return these only if your hook processed the input without errors.

  • claims A json containing the updated claims after the hook has been run.

Examples

Local Development

Unlike the hosted platform, the local development dashboard does not have a user interface for linking a Hook. Instead, edit config.toml to link an Auth Hook and run it with your local setup. Modify the auth.hook.<hook_name> field and set uri to a value of pg-functions://postgres/<schema>/<function_name>

For instance, the config.toml for a Custom Access Token Hook which uses the function public.custom_access_token_hook:


_10
...
_10
_10
[auth.hook.custom_access_token]
_10
enabled = true
_10
uri = "pg-functions://postgres/public/custom_access_token_hook"
_10
_10
...

Save your Auth Hook as a migration in order to version the Auth Hook and share it with other team members. Run supabase migration new to create a migration.

Debugging Your Hook

Test the Postgres Function in isolation before enabling the hook by connecting to your database with psql and running select <your_function_name>. Where necessary, use RAISE statements to print information to the terminal.