Skip to content
Auth

多因素认证验证钩子

你可以通过钩子给 Supabase 多因素认证实现 添加额外的检查。例如,你可以:

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

  • 限制在一段时间内进行的验证尝试次数。
  • 登出那些验证尝试太多次失败的用户。
  • 统计、限速或禁止登录。

输入

Supabase Auth 会向你的 hook 发送包含这些字段的负载:

🌐 Supabase Auth will send a payload containing these fields to your hook:

字段类型描述
factor_idstring正在验证的多因素认证因素的唯一标识符
factor_typestringtotp 或 phone
user_idstring用户的唯一标识符
validboolean验证尝试是否有效。对于 TOTP,这意味着六位数代码正确(true)或错误(false)。
{
"factor_id": "6eab6a69-7766-48bf-95d8-bd8f606894db",
"user_id": "3919cb6e-4215-4478-a960-6d3454326cec",
"valid": true
}

输出

如果你的钩子没有错误地处理输入,就返回这个。

🌐 Return this if your hook processed the input without errors.

字段类型描述
decisionstring关于是否允许认证继续的决定。使用 reject 拒绝验证尝试,并将用户从所有活跃会话中注销。使用 continue 来使用默认的 Supabase Auth 行为。
messagestring如果决定是 reject,显示给用户的消息。
{
"decision": "reject",
"message": "You have exceeded maximum number of MFA attempts."
}

你们公司要求用户输入错误的多因素验证代码,每次间隔不得少于2秒。

🌐 Your company requires that a user can input an incorrect MFA Verification code no more than once every 2 seconds.

创建一个表格来记录用户最后一次多因素认证错误尝试的时间。

🌐 Create a table to record the last time a user had an incorrect MFA verification attempt for a factor.

create table public.mfa_failed_verification_attempts (
user_id uuid not null,
factor_id uuid not null,
last_failed_at timestamp not null default now(),
primary key (user_id, factor_id)
);

创建一个钩子来读取和写入这个表的信息。例如:

🌐 Create a hook to read and write information to this table. For example:

create function public.hook_mfa_verification_attempt(event jsonb)
returns jsonb
language plpgsql
as $$
declare
last_failed_at timestamp;
begin
if event->'valid' is true then
-- code is valid, accept it
return jsonb_build_object('decision', 'continue');
end if;
select last_failed_at into last_failed_at
from public.mfa_failed_verification_attempts
where
user_id = event->'user_id'
and
factor_id = event->'factor_id';
if last_failed_at is not null and now() - last_failed_at < interval '2 seconds' then
-- last attempt was done too quickly
return jsonb_build_object(
'error', jsonb_build_object(
'http_code', 429,
'message', 'Please wait a moment before trying again.'
)
);
end if;
-- record this failed attempt
insert into public.mfa_failed_verification_attempts
(
user_id,
factor_id,
last_failed_at
)
values
(
event->'user_id',
event->'factor_id',
now()
)
on conflict do update
set last_failed_at = now();
-- finally let Supabase Auth do the default behavior for a failed attempt
return jsonb_build_object('decision', 'continue');
end;
$$;
-- Assign appropriate permissions and revoke access
grant all
on table public.mfa_failed_verification_attempts
to supabase_auth_admin;
revoke all
on table public.mfa_failed_verification_attempts
from authenticated, anon, public;