如何在AWS Amplify中实现登录后重定向至用户来源页面?
解决AWS Amplify未登录页面拦截与登录后原页面重定向问题
1. 基础配置:初始化Amplify并启用Google登录
首先完成Amplify Auth的基础配置,添加Google作为第三方登录提供商。
在amplify/auth/resource.ts中配置Google登录:
import { defineAuth } from '@aws-amplify/backend'; export const auth = defineAuth({ loginWith: { externalProviders: { google: { clientId: process.env.GOOGLE_CLIENT_ID!, scopes: ['email', 'profile'] } } }, userAttributes: { email: { required: true } } });
在前端入口文件(如main.tsx)初始化Amplify:
import { Amplify } from 'aws-amplify'; import awsExports from './aws-exports'; Amplify.configure(awsExports);
2. 实现路由保护组件
创建ProtectedRoute组件,拦截未登录用户的访问请求,并记录目标页面路径:
import { Navigate, Outlet, useLocation } from 'react-router-dom'; import { useAuthenticator } from '@aws-amplify/ui-react'; export const ProtectedRoute = () => { const { user } = useAuthenticator((context) => [context.user]); const location = useLocation(); if (!user) { // 未登录时跳转到登录页,携带原访问路径作为重定向参数 return <Navigate to="/login" state={{ from: location.pathname }} replace />; } return <Outlet />; };
3. 登录页与重定向逻辑实现
创建LoginPage组件,使用Amplify官方UI组件完成登录,并在登录成功后跳转回原页面:
import { useEffect } from 'react'; import { Authenticator } from '@aws-amplify/ui-react'; import '@aws-amplify/ui-react/styles.css'; import { useLocation, useNavigate } from 'react-router-dom'; export const LoginPage = () => { const location = useLocation(); const navigate = useNavigate(); // 获取原访问路径,默认跳转到首页 const redirectPath = location.state?.from || '/'; useEffect(() => { // 监听登录状态,认证成功后执行重定向 const unsubscribe = Authenticator.subscribe(({ authStatus }) => { if (authStatus === 'authenticated') { navigate(redirectPath, { replace: true }); } }); return unsubscribe; }, [navigate, redirectPath]); return ( <Authenticator> {(signOut, user) => ( <div> <p>欢迎回来,{user?.email}</p> <button onClick={signOut}>退出登录</button> </div> )} </Authenticator> ); };
4. 配置路由结构
在App.tsx中整合路由,用ProtectedRoute包裹所有需要保护的页面:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import { ProtectedRoute } from './components/ProtectedRoute'; import { LoginPage } from './pages/LoginPage'; import { ProjectNew } from './pages/ProjectNew'; import { UserProfile } from './pages/UserProfile'; import { Home } from './pages/Home'; function App() { return ( <Router> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<LoginPage />} /> {/* 受保护页面组 */} <Route element={<ProtectedRoute />}> <Route path="/project/new" element={<ProjectNew />} /> <Route path="/user/profile" element={<UserProfile />} /> </Route> {/* 404 fallback */} <Route path="*" element={<Navigate to="/" replace />} /> </Routes> </Router> ); } export default App;
关键注意事项
- 确保在Google Cloud Console中配置正确的OAuth回调URL,格式为
https://<你的Amplify域名>/auth/google/callback(本地开发用http://localhost:3000/auth/google/callback)。 useAuthenticator钩子用于实时监听用户登录状态,Authenticator.subscribe则捕获登录成功的事件触发重定向。
内容的提问来源于stack exchange,提问作者aadilraza339
相关产品推荐
相关产品推荐

