新闻详情

新闻详情

首页 / 资讯中心 / 详情

Refine 认证 Hook 全解析:useLogin 到 usePermissions 的 React 认证 Hook 体系与 authProvider 映射

发布时间:2026/9/13 18:21:43来源:尧图网络
Refine 认证 Hook 全解析:useLogin 到 usePermissions 的 React 认证 Hook 体系与 authProvider 映射
Refine 认证 Hook 全解析useLogin 到 usePermissions 的 React 认证 Hook 体系与 authProvider 映射【免费下载链接】refineA React Framework for building internal tools, admin panels, dashboards B2B apps with unmatched flexibility.项目地址: https://gitcode.com/GitHub_Trending/re/refine本篇以 Refine 官方文档中「Authentication Hooks」参考表为主体逐一展开 9 个认证 Hook 与authProvider方法的映射关系、返回值类型、自定义页面用法登录、注册、找回密码、改密、权限等并结合packages/core源码印证每个 Hook 底层的 react-query 实现机制。读完你可以掌握如何在 Refine 中自定义登录/注册/找回密码页面、处理登录失败通知、实现注册后自动登录与 401 类错误的统一登出逻辑。认证 Hook 与 authProvider 方法的映射总览Refine 把authProvider上定义好的每个方法都包装成了对应的 React HookHook 统一从refinedev/core导入。官方参考表见 auth-hooks.md的完整内容如下Hook对应 authProvider 方法说明useRegisterregister注册新用户useLoginlogin认证并登录用户useIsAuthenticatedcheck表中标注为checkAuth检查用户是否已认证useLogoutlogout登出当前用户useOnErroronError表中标注为handleError处理认证相关错误useGetIdentitygetIdentity获取用户身份信息useUpdatePasswordupdatePassword更新用户密码useForgotPasswordforgotPassword发起找回密码流程usePermissionsgetPermissions获取用户权限需要说明的一处历史命名参考表沿用了旧版方法名checkAuth、handleError。对照当前仓库 authProvider 类型定义v5 版本的AuthProvider接口实际方法名为check与onErrorexport type AuthProvider { login: (params: any) PromiseAuthActionResponse; logout: (params: any) PromiseAuthActionResponse; check: (params?: any) PromiseCheckResponse; onError: (error: any) PromiseOnErrorResponse; register?: (params: any) PromiseAuthActionResponse; forgotPassword?: (params: any) PromiseAuthActionResponse; updatePassword?: (params: any) PromiseAuthActionResponse; getPermissions?: ( params?: Recordstring, any, ) PromisePermissionResponse; getIdentity?: (params?: any) PromiseIdentityResponse; };从类型定义可以看到login、logout、check、onError是四个必选方法register、forgotPassword、updatePassword、getPermissions、getIdentity为可选方法——即你的authProvider可以只实现其中一部分对应的 Hook 依然可用。这 9 个 Hook 的导出入口统一在 auth hooks 的 index 中export { usePermissions } from ./usePermissions; export { useGetIdentity } from ./useGetIdentity; export { useLogout } from ./useLogout; export { useLogin } from ./useLogin; export { useRegister } from ./useRegister; export { useForgotPassword } from ./useForgotPassword; export { useUpdatePassword } from ./useUpdatePassword; export { useIsAuthenticated } from ./useIsAuthenticated; export { useOnError } from ./useOnError;底层机制react-query 与统一的响应类型所有认证 Hook 都构建在tanstack/react-query之上分为两类Mutation 型useLogin、useLogout、useRegister、useForgotPassword、useUpdatePassword、useOnError底层是useMutation返回isSuccess、isError等状态通过mutate触发认证动作Query 型useIsAuthenticated、useGetIdentity、usePermissions底层是useQuery在渲染时自动拉取数据。动作型 Hook 的返回值data统一为AuthActionResponse类型定义在 contexts/auth/types.tstype SuccessNotificationResponse { message: string; description?: string; }; type AuthActionResponse { success: boolean; redirectTo?: string; error?: Error; [key: string]: unknown; successNotification?: SuccessNotificationResponse; };各字段含义对login/logout/register/forgotPassword/updatePassword通用success布尔值标识操作是否成功。若为false框架会自动弹出一条错误通知error若提供通知内容会包含该错误的name和message若未提供则显示各动作的默认通用错误例如登录为{ name: Login Error, message: Invalid credentials }登出为{ name: useLogout Error, message: Something went wrong during logout }redirectTo若存在应用会跳转到该 URLsuccessNotification若提供则显示一条成功通知结构为{ message, description? }[key: string]响应中可携带任意额外数据。一个值得注意的设计原则见 types.ts 顶部注释authProvider 的方法应当始终 resolve即便用户未认证也不 reject而是通过authenticated: false、redirectTo、logout等字段携带处理所需的信息。因此各文档统一强调当success为false时useMutation的onError回调不会被触发错误处理应该依赖onSuccess回调里的data.success判断。useLogin 的源码实现以 useLogin 源码 为例可以看到框架在 mutation 成功后自动完成的通知与跳转编排onSuccess: async ({ success, redirectTo, error, successNotification }) { if (success) { close?.(login-error); // 关闭上一次遗留的登录错误通知 if (successNotification) { open?.(buildSuccessNotification(successNotification)); } } if (error || !success) { open?.(buildNotification(error)); // 弹错误通知默认 Invalid credentials } if (success) { if (to) { go({ to: to, type: replace }); // 优先跳转 URL 中 ?to 指定的目标页 } else if (redirectTo) { go({ to: redirectTo, type: replace }); } } setTimeout(() { invalidateAuthStore(); // 32ms 后失效认证缓存identity/permissions }, 32); },两个实现细节值得关注登录回跳useLogin内部通过useParsed()读取 URL 中的to查询参数const to parsed.params?.to;。从源码结构看被Authenticated拦截后重定向到登录页的链接通常会携带?to/目标页登录成功后会优先replace回该目标页其次才是redirectTo。认证缓存失效登录成功后调用useInvalidateAuthStore失效 react-query 中身份与权限相关查询保证useGetIdentity/usePermissions立即拿到新会话数据。useLogin自定义登录页与错误处理Refine 提供默认登录页但你可以完全自定义。基本用法摘自 useLogin 文档import { useLogin } from refinedev/core; import { Form } from antd; type LoginVariables { username: string; password: string; }; export const LoginPage () { const { mutate: login } useLoginLoginVariables(); const onSubmit (event: React.FormEventHTMLFormElement) { event.preventDefault(); login({ username: event.currentTarget.username.value, password: event.currentTarget.password.value, }); }; return ( Form onFinish{onSubmit} {/* 用户名/密码输入框 */} /Form ); };由于authProvider.login的参数不受类型限制mutate接受任意对象可通过类型参数约束变量结构const { mutate: login } useLogin{ username: string; password: string }();登录后重定向在调用时传入redirectPath并在authProvider的login方法中读取import { useLogin } from refinedev/core; const { mutate: login } useLogin(); login({ redirectPath: /custom-url });import type { AuthProvider } from refinedev/core; const authProvider: AuthProvider { // ... login: async ({ redirectPath }) { // ... return { success: true, redirectTo: redirectPath, successNotification: { message: Login Successful, description: You have successfully logged in., }, }; }, };错误处理由于authProvider方法始终返回 resolved promise错误判断放在onSuccess中import { useLogin } from refinedev/core; const { mutate: login } useLogin(); login( { email: refineexample.com, password: refine, }, { onSuccess: (data) { if (!data.success) { // 处理错误 } // 处理成功 }, }, );注意useLogin的onError回调只在 promise 被 reject 时触发success: false不会走到它。useLogout登出与跳转useLogout调用authProvider.logout返回值同样是AuthActionResponse见 useLogout 文档。自定义登出按钮import { useLogout } from refinedev/core; export const LogoutButton () { const { mutate: logout } useLogout(); return button onClick{() logout()}Logout/button; };登出后重定向的写法与登录完全对称——调用时传redirectPath在authProvider.logout中回传为redirectToimport type { AuthProvider } from refinedev/core; const authProvider: AuthProvider { // ... logout: async ({ redirectPath }) { // ... return { success: true, redirectTo: redirectPath, successNotification: { message: Logout Successful, description: You have successfully logged out., }, }; }, };logout未提供error时的通用失败提示为{ name: useLogout Error, message: Something went wrong during logout }。useIsAuthenticated认证检查与Authenticated组件useIsAuthenticated调用authProvider.check方法底层是useQuery见 useIsAuthenticated 文档。返回数据为CheckResponsetype CheckResponse { authenticated: boolean; redirectTo?: string; logout?: boolean; error?: Error; };authenticated用户是否已认证redirectTo需要认证时跳转的 URLlogout是否应当调用logouterror检查过程中产生的错误对象。典型场景公开页面中的私有字段。假设check逻辑如下const authProvider: AuthProvider { // ... check: () { if (localStorage.getItem(email)) { return { authenticated: true }; } return { authenticated: false, error: { message: Check failed, name: Not authenticated }, logout: true, redirectTo: /login, }; }, };据此可以实现一个Authenticated包装组件Refine 内置的Authenticated组件即用此 Hookimport { useIsAuthenticated, useGo } from refinedev/core; export const Authenticated: React.FCAuthenticatedProps ({ children, fallback, loading, }) { const { isLoading, data } useIsAuthenticated(); const go useGo(); if (isLoading) { return {loading}/ || null; } if (data.error) { if (!fallback) { go({ to: data.redirectTo, type: replace }); return null; } return {fallback}/; } if (data.authenticated) { return {children}/; } return null; };之后即可在任意页面包裹敏感内容import { Authenticated } from components/authenticated; export const PostShow: React.FC () ( div Authenticated spanOnly authenticated users can see/span /Authenticated /div );源码侧useIsAuthenticated/index.ts有两个细节查询固定retry: false认证检查不重试且当check未返回有效值时回退为{ authenticated: true }——即未定义check方法时默认视为已认证。useOnError统一的错误兜底自动登出useOnError调用authProvider.onError返回数据为type OnErrorResponse { redirectTo?: string; logout?: boolean; error?: Error; };处理流程redirectTo有值则跳转logout为true时框架自动调用logouterror为错误对象见 useOnError 文档。内部用途Refine 在数据层 HookuseList、useCreate等内部就使用了useOnError。任何数据 Hook 抛出的错误都会被传入authProvider.onError从而可以统一决定跳转或登出。例如针对状态码418做安全登出const authProvider: AuthProvider { // ... onError: (error) { const status error.status; if (status 418) { return { logout: true, redirectTo: /login, error: new Error(error), }; } return {}; }, };手动使用比如支付请求被 API 拒绝捕获后交给onError走统一逻辑import { useOnError } from refinedev/core; const { mutate: onError } useOnError(); fetch(http://example.com/payment) .then(() console.log(Success)) .catch((error) onError(error));从 useOnError 源码 可以看到框架优先处理logout: true携带redirectPath调用useLogout否则再按redirectTo执行replace跳转另外若你的authProvider没有实现onErrormutation 会退化为空操作() ({})不会抛错。useRegister注册与注册后自动登录useRegister调用authProvider.register返回AuthActionResponse见 useRegister 文档。自定义注册页import { useRegister } from refinedev/core; type RegisterVariables { email: string; password: string; }; export const RegisterPage () { const { mutate: register } useRegisterRegisterVariables(); const onSubmit (e: React.FormEventHTMLFormElement) { e.preventDefault(); const values { email: e.currentTarget.email.value, password: e.currentTarget.password.value, }; register(values); }; return ( form onSubmit{onSubmit} labelEmail/label input nameemail valuetestrefine.com / labelPassword/label input namepassword valuerefine / button typesubmitSubmit/button /form ); };register未提供error时的默认失败提示为{ name: Register Error, message: Error while registering }。注册成功后自动登录在onSuccess回调里直接调用useLogin实现注册即登录import { useRegister, useLogin } from refinedev/core; type FormVariables { email: string; password: string; }; export const RegisterPage () { const { mutate: register } useRegisterFormVariables(); const { mutate: login } useLoginFormVariables(); const onSubmit (e: React.FormEventHTMLFormElement) { e.preventDefault(); const values { email: e.currentTarget.email.value, password: e.currentTarget.password.value, }; register(values, { onSuccess: () { login(values); }, }); }; return ( form onSubmit{onSubmit} labelEmail/label input nameemail valuetestrefine.com / labelPassword/label input namepassword valuerefine / button typesubmitSubmit/button /form ); };注册后的重定向同样通过register({ redirectPath: /custom-url })authProvider.register中回传redirectTo: redirectPath实现。useForgotPassword 与 useUpdatePassword密码找回与重置useForgotPassword调用authProvider.forgotPassword见 useForgotPassword 文档自定义找回页只需提交邮箱import { useForgotPassword } from refinedev/core; type forgotPasswordVariables { email: string; }; export const ForgotPasswordPage () { const { mutate: forgotPassword } useForgotPasswordforgotPasswordVariables(); const onSubmit (e: React.FormEventHTMLFormElement) { e.preventDefault(); forgotPassword({ email: e.currentTarget.email.value, }); }; return ( form onSubmit{onSubmit} labelEmail/label input nameemail valuetestrefine.com / button typesubmitSubmit/button /form ); };useUpdatePassword调用authProvider.updatePassword见 useUpdatePassword 文档用于重置密码页。它的特殊之处在于authProvider的updatePassword参数中带有queryStrings可以把重置邮件链接中的 token 直接透传给业务逻辑。例如重置链接为YOUR_DOMAIN/update-password?token123时import type { AuthProvider } from refinedev/core; const authProvider: AuthProvider { // ... updatePassword: (params) { // query strings 可以通过 params.queryStrings 访问 console.log(params.token); if (params.token 123) { // 执行你的密码更新逻辑 } }, };页面侧用法与其他动作 Hook 一致import { useUpdatePassword } from refinedev/core; const { mutate: updatePassword } useUpdatePassword{ newPassword: string }();两者的重定向与错误处理模式同前success为false时在onSuccess中判断未提供error时的默认提示分别为{ name: Forgot Password Error, message: Invalid credentials }和{ name: Update Password Error, message: Error while resetting password }。useGetIdentity获取用户身份useGetIdentity调用authProvider.getIdentity底层是useQuery见 useGetIdentity 文档返回值无固定类型由你的getIdentity决定。在authProvider中const authProvider: AuthProvider { // ... getIdentity: async () { return { id: 1, fullName: Jane Doe, }; }, };任意位置读取身份信息例如侧边栏显示用户名import { useGetIdentity } from refinedev/core; export const User () { const { data: identity } useGetIdentityIIdentity(); return span{identity?.fullName}/span; }; type IIdentity { id: number; fullName: string; };usePermissions权限驱动的 UI 控制usePermissions调用authProvider.getPermissions底层是useQuery见 usePermissions 文档。getPermissions支持传入参数从源码结构看常用于按租户等维度取权限const authProvider: AuthProvider { // ... getPermissions: async (params) { if (params) { // 例如按 params.tenantId 查询该租户下的角色 return [admin]; } return [admin]; }, };在列表页根据权限控制canCreateimport { usePermissions } from refinedev/core; import { List } from refinedev/antd; export const PostList: React.FC () { const { data: permissionsData } usePermissions({ params: { tenantId: id }, // 可传参给 getPermissions }); return List canCreate{permissionsData?.includes(admin)}.../List; };使用建议与源码索引统一错误处理五个动作型 Hooklogin/logout/register/forgotPassword/updatePassword都遵循「authProvider方法始终 resolve」的约定错误分支要写在onSuccess的!data.success判断里而不是onError重定向双通道既可以用响应里的redirectTo由authProvider决定也可以在调用时传redirectPath由页面决定登录场景还会被 URL 中的?to参数优先覆盖认证缓存登录成功后框架延迟 32ms 调用invalidateAuthStore见 useLogin 源码因此useGetIdentity、useIsAuthenticated、usePermissions等查询会自动刷新。本文涉及的仓库文件索引Hook 汇总与映射表documentation/src/partials/auth-provider/auth-hooks.md各 Hook 官方文档useLogin、useLogout、useIsAuthenticated、useOnError、useGetIdentity、useRegister、useForgotPassword、useUpdatePassword、usePermissionsauthProvider 总览documentation/docs/authentication/auth-provider/index.md核心源码packages/core/src/hooks/auth/、类型定义 packages/core/src/contexts/auth/types.ts【免费下载链接】refineA React Framework for building internal tools, admin panels, dashboards B2B apps with unmatched flexibility.项目地址: https://gitcode.com/GitHub_Trending/re/refine创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

动态压力传感器选型:响应时间与频率带宽的工程真相 2026/9/13 19:39:49

动态压力传感器选型:响应时间与频率带宽的工程真相

1. 一个被忽略的“读数正确但结果失效”现场上周在帮一家做液压系统故障诊断的客户做传感器选型复盘时,我亲眼看到他们用一台标称精度0.5%FS的普通压阻式压力传感器,连续三天测同一台注塑机保压阶段的压力曲线——数据看起来非常“漂亮”:波形…

阅读更多 →
Telegraf 插件状态持久化(State Persistence)开发指南:从 StatefulPlugin 接口到 statefile 落地 2026/9/13 19:39:49

Telegraf 插件状态持久化(State Persistence)开发指南:从 StatefulPlugin 接口到 statefile 落地

Telegraf 插件状态持久化(State Persistence)开发指南:从 StatefulPlugin 接口到 statefile 落地 【免费下载链接】telegraf Agent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data. 项目地…

阅读更多 →
FunASR Python SDK 实战:AutoModel 构建、推理、VAD 流水线与流式 Cache 生命周期全解析 2026/9/13 19:39:49

FunASR Python SDK 实战:AutoModel 构建、推理、VAD 流水线与流式 Cache 生命周期全解析

FunASR Python SDK 实战:AutoModel 构建、推理、VAD 流水线与流式 Cache 生命周期全解析 【免费下载链接】FunASR Open-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-…

阅读更多 →
Vector Pulsar Source 接入指南:从 Apache Pulsar 主题采集可观测数据 2026/9/13 19:39:49

Vector Pulsar Source 接入指南:从 Apache Pulsar 主题采集可观测数据

Vector Pulsar Source 接入指南:从 Apache Pulsar 主题采集可观测数据 【免费下载链接】vector A high-performance observability data pipeline. 项目地址: https://gitcode.com/GitHub_Trending/vect/vector Apache Pulsar 是流式计算场景下广泛使用的云原…

阅读更多 →
Lima 磁盘管理完全指南:独立数据盘(limactl disk)与主磁盘扩容实战 2026/9/13 19:39:49

Lima 磁盘管理完全指南:独立数据盘(limactl disk)与主磁盘扩容实战

Lima 磁盘管理完全指南:独立数据盘(limactl disk)与主磁盘扩容实战 【免费下载链接】lima Linux virtual machines, with a focus on running containers 项目地址: https://gitcode.com/GitHub_Trending/lim/lima 本指南围绕 Lima 的…

阅读更多 →
Opik Backend 端点权限(@RequiredPermissions)接入指南:从权限枚举到 JAX-RS 资源注解的完整实践 2026/9/13 19:36:48

Opik Backend 端点权限(@RequiredPermissions)接入指南:从权限枚举到 JAX-RS 资源注解的完整实践

Opik Backend 端点权限(RequiredPermissions)接入指南:从权限枚举到 JAX-RS 资源注解的完整实践 【免费下载链接】comet-llm Debug, evaluate, and monitor your LLM applications, RAG systems, and agentic workflows with comprehensive t…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞