要在 JavaScript 中使用 Firebase 身份验证保护路由,您需要先设置 Firebase 应用程序、安装必要的库,并配置路由
npm install firebase react-router-dom
firebaseConfig.js
。import { initializeApp } from "firebase/app";
import { getAuth } from "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",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export { auth };
PrivateRoute
组件以保护您的路由:// PrivateRoute.js
import React from "react";
import { Route, Navigate, useLocation } from "react-router-dom";
import { useAuth } from "./useAuth";
function PrivateRoute({ children, ...rest }) {
const { currentUser } = useAuth();
const location = useLocation();
return (
<Route
{...rest}
render={({ location }) =>
currentUser ? (
children
) : (
<Navigate to="/login" state={{ from: location }} />
)
}
/>
);
}
export default PrivateRoute;
useAuth
钩子:// useAuth.js
import { useContext, useEffect, useState } from "react";
import { AuthContext } from "./AuthContext";
import { getAuth } from "firebase/auth";
function useAuth() {
const { currentUser } = useContext(AuthContext);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = getAuth().onAuthStateChanged((user) => {
setLoading(false);
});
return () => unsubscribe();
}, []);
if (loading) {
return null;
}
return { currentUser };
}
export default useAuth;
AuthContext
:// AuthContext.js
import React, { createContext, useContext, useState } from "react";
import { getAuth } from "firebase/auth";
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const auth = getAuth();
const [currentUser, setCurrentUser] = useState(null);
return (
<AuthContext.Provider value={{ auth, currentUser, setCurrentUser }}>
{children}
</AuthContext.Provider>
);
}
// App.js
import React from "react";
import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
import { AuthProvider } from "./AuthContext";
import PrivateRoute from "./PrivateRoute";
import LoginPage from "./pages/LoginPage";
import HomePage from "./pages/HomePage";
function App() {
return (
<Router>
<AuthProvider>
<Switch>
<Route path="/login" component={LoginPage} />
<PrivateRoute exact path="/" component={HomePage} />
<Redirect to="/" />
</Switch>
</AuthProvider>
</Router>
);
}
export default App;
现在,您已经使用 Firebase 身份验证保护了路由。未登录的用户在访问受保护的路由时将被重定向到登录页面。
领取专属 10元无门槛券
手把手带您无忧上云