如何结合React Context使用新版AWS Amplify Authenticator并捕获流程阶段
AWS Amplify Authenticator 流程响应捕获与自定义逻辑实现
核心思路:通过Authenticator内置钩子+Amplify Auth API,介入认证关键节点,实现自定义状态管理与清理逻辑
1. 捕获注册提交事件,标记账户为Pending
Authenticator提供onSignUpSubmit钩子,在用户提交注册表单后触发。你可以在这里获取注册响应,将状态存入全局上下文,并标记账户为pending:
import { Authenticator } from '@aws-amplify/ui-react'; import { Auth } from 'aws-amplify'; import { useAuthContext } from './your-auth-context'; function App() { const { setAuthState } = useAuthContext(); const handleSignUpSubmit = async (formData) => { try { // 手动调用Auth注册API,获取完整响应 const signUpResponse = await Auth.signUp({ username: formData.username, password: formData.password, attributes: { email: formData.email } }); // 更新全局上下文状态 setAuthState({ step: 'pending_verification', userId: signUpResponse.userSub, email: formData.email }); // 同步到后端,标记账户为pending(用于后续清理) await fetch('/api/mark-user-pending', { method: 'POST', body: JSON.stringify({ userId: signUpResponse.userSub }) }); } catch (err) { console.error('注册失败:', err); } }; return ( <Authenticator onSignUpSubmit={handleSignUpSubmit} > {/* 应用内容 */} </Authenticator> ); }
2. 捕获验证码验证事件,激活账户
使用onVerifySubmit钩子监听验证码提交,验证通过后更新账户激活状态:
const handleVerifySubmit = async (formData) => { const { username, verificationCode } = formData; const { userId } = useAuthContext(); try { // 验证验证码 await Auth.confirmSignUp(username, verificationCode); // 更新全局上下文为已激活状态 setAuthState({ step: 'authenticated', userId, isActive: true }); // 通知后端激活账户 await fetch('/api/activate-user', { method: 'POST', body: JSON.stringify({ userId }) }); } catch (err) { console.error('验证码验证失败:', err); } }; // 在Authenticator中挂载钩子 <Authenticator onSignUpSubmit={handleSignUpSubmit} onVerifySubmit={handleVerifySubmit} > {/* ... */} </Authenticator>
3. 处理中途退出的账户清理
前端主动清理(补充方案)
如果用户主动退出注册流程,可在组件卸载时尝试删除未验证账户:
import { useEffect } from 'react'; function SignUpFlow() { const { userId } = useAuthContext(); useEffect(() => { return () => { // 组件卸载时,若处于pending状态则删除账户 if (userId) { Auth.deleteUser().catch(err => { console.warn('前端删除失败,将由后端定时清理:', err); }); } }; }, [userId]); return <Authenticator {...props} />; }
后端定时清理(可靠方案)
前端清理可能存在遗漏,建议结合后端实现:
- 注册时在数据库记录账户创建时间与pending状态
- 用DynamoDB的TTL功能,设置x天后自动删除未激活账户
- 或通过Lambda定时任务,扫描清理超期的pending账户
注意事项
- 确保
@aws-amplify/ui-react版本在v3及以上,支持上述钩子 - 手动调用Auth API时,可通过
overrideDefaults禁用组件默认逻辑,避免冲突 - 全局上下文状态可结合localStorage持久化,防止页面刷新丢失
内容的提问来源于stack exchange,提问作者Good Stuff
相关产品推荐
相关产品推荐

