You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Supabase本地实例JWT创建钩子不生效,JWT payload为空求助

解决本地Supabase实例JWT钩子不触发的问题

核心问题

生产环境中custom_access_token_hook能正常给JWT添加user_role字段,但本地实例里JWT payload为空,函数存在但未触发。

解决步骤

  • 确认钩子已注册到Auth服务
    仅存在函数不够,需将其关联到Supabase Auth的access_token钩子:

    1. 先查询是否已注册:
      select * from auth.hooks where hook_type = 'access_token';
      
    2. 若查询结果为空,执行注册语句:
      insert into auth.hooks (hook_type, hook_function)
      values ('access_token', 'public.custom_access_token_hook')
      on conflict (hook_type) do update set hook_function = 'public.custom_access_token_hook';
      
  • 检查函数与表的权限
    Auth服务通过authenticator角色执行钩子,需确保该角色有足够权限:

    1. 赋予函数执行权限:
      grant execute on function public.custom_access_token_hook(jsonb) to authenticator;
      
    2. 赋予user_roles表的查询权限:
      grant select on public.user_roles to authenticator;
      
  • 验证本地配置文件
    打开supabase/config.toml,确认没有禁用钩子的配置:

    • 确保不存在disable_hooks = true,若有则改为disable_hooks = false
  • 重启本地Supabase服务
    配置和权限修改后,必须重启服务才能生效:

    supabase stop
    supabase start
    
  • 测试钩子触发情况

    1. 重新登录用户,解码JWT(可使用jwt.io工具)查看payload是否包含user_role字段
    2. 可选调试:在钩子函数开头添加日志代码:
      raise notice 'custom_access_token_hook triggered for user: %', (event->>'user_id')::uuid;
      
      然后查看Auth日志:
      supabase logs -f auth
      
      若能看到日志输出,说明钩子已正常触发。

你的钩子函数代码

declare
  claims jsonb;
  user_role public.app_role;
begin
  -- Check if the user is marked as admin in the profiles table
  select role into user_role from public.user_roles where user_id = (event->>'user_id')::uuid;

  claims := event->'claims';

  if user_role is not null then
    -- Set the claim
    claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role));
  else
    claims := jsonb_set(claims, '{user_role}', 'null');
  end if;

  -- Update the 'claims' object in the original event
  event := jsonb_set(event, '{claims}', claims);

  -- Return the modified or original event
  return event;
end;

内容的提问来源于stack exchange,提问作者Fliegel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 03:04:55