Supabase本地实例JWT创建钩子不生效,JWT payload为空求助
解决本地Supabase实例JWT钩子不触发的问题
核心问题
生产环境中custom_access_token_hook能正常给JWT添加user_role字段,但本地实例里JWT payload为空,函数存在但未触发。
解决步骤
确认钩子已注册到Auth服务
仅存在函数不够,需将其关联到Supabase Auth的access_token钩子:- 先查询是否已注册:
select * from auth.hooks where hook_type = 'access_token'; - 若查询结果为空,执行注册语句:
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角色执行钩子,需确保该角色有足够权限:- 赋予函数执行权限:
grant execute on function public.custom_access_token_hook(jsonb) to authenticator; - 赋予
user_roles表的查询权限:grant select on public.user_roles to authenticator;
- 赋予函数执行权限:
验证本地配置文件
打开supabase/config.toml,确认没有禁用钩子的配置:- 确保不存在
disable_hooks = true,若有则改为disable_hooks = false
- 确保不存在
重启本地Supabase服务
配置和权限修改后,必须重启服务才能生效:supabase stop supabase start测试钩子触发情况
- 重新登录用户,解码JWT(可使用jwt.io工具)查看payload是否包含
user_role字段 - 可选调试:在钩子函数开头添加日志代码:
然后查看Auth日志:raise notice 'custom_access_token_hook triggered for user: %', (event->>'user_id')::uuid;
若能看到日志输出,说明钩子已正常触发。supabase logs -f auth
- 重新登录用户,解码JWT(可使用jwt.io工具)查看payload是否包含
你的钩子函数代码
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
相关产品推荐
相关产品推荐

