要在React应用中使用Firebase身份验证检查来保护路由,您需要结合使用React Router和Firebase Auth
react-router-dom
和firebase
这两个库。如果没有,请使用以下命令安装:npm install react-router-dom firebase
// src/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
// src/ProtectedRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { auth } from './firebase';
function ProtectedRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={(props) =>
auth.currentUser ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
}
export default ProtectedRoute;
ProtectedRoute
组件来保护需要身份验证的路由:// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import Login from './Login';
import Home from './Home';
import Dashboard from './Dashboard';
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<ProtectedRoute path="/dashboard" component={Dashboard} />
<Route path="/" exact component={Home} />
</Switch>
</Router>
);
}
export default App;
现在,当用户尝试访问/dashboard
路由时,如果用户未登录,将重定向到/login
页面。在登录后,用户将被重定向回他们原来试图访问的页面。
领取专属 10元无门槛券
手把手带您无忧上云