ara*_* ks 6 node.js reactjs firebase-authentication firebaseui next.js
我在 Next.js 应用程序中使用 Firebase 进行用户身份验证。我想保护客户端的用户。我使用 firebase firebaseui react-firebaseUI 来实现 Google Auth。如何保护客户端本身的路由
const uiConfig = {
signInFlow: "popup",
signInSuccessUrl: "/dashboard",
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
}
Run Code Online (Sandbox Code Playgroud)
我想保护仪表板路线。提前致谢 :)
首先,您需要维护一个包含所有公共和受保护路由的路由器。
import React from 'react';
import {
Route,
Switch,
BrowserRouter,
} from 'react-router-dom';
import ProtectedRoute from './Protected';
import Foo from './Foo';
import Bar from './Bar';
const Routes = () => (
<BrowserRouter>
<Switch>
// public route
<Route exact path="/foo" component={Foo} />
// protected route
<ProtectedRoute exact path="/bar" component={Bar} />
// if user hits a URL apart from the above ones, render a 404 component
<Route path="*" component={NotFound} />
</Switch>
</BrowserRouter>
);
export default Routes;
Run Code Online (Sandbox Code Playgroud)
这是保护路由,将处理是否应允许用户根据其身份验证状态访问应用程序上的保护页面。
import React from 'react';
import { useAuthStatus } from '../hooks';
import Spinner from '../Spinner';
import UnAuthorised from '../UnAuthorised';
const ProtectedRoute = ({ component: Component }) => {
// a custom hook to keep track of user's auth status
const { loggedIn, checkingStatus } = useAuthStatus();
return (
<>
{
// display a spinner while auth status being checked
checkingStatus
? <Spinner />
: loggedIn
// if user is logged in, grant the access to the route
// note: in this example component is Bar
? <Component />
// else render an unauthorised component
// stating the reason why it cannot access the route
: <UnAuthorised />
}
</>
);
};
export default ProtectedRoute;
Run Code Online (Sandbox Code Playgroud)
嗯,这是用于跟踪用户登录和注销的自定义挂钩。
import { useEffect, useState } from 'react';
import { firebase } from '../config';
export const useAuthListener = (): void => {
// assume user to be logged out
const [loggedIn, setLoggedIn] = useState(false);
// keep track to display a spinner while auth status is being checked
const [checkingStatus, setCheckingStatus] = useState(true);
useEffect(() => {
// auth listener to keep track of user signing in and out
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setLoggedIn(true);
}
setCheckingStatus(false);
});
}, []);
return { loggedIn, checkingStatus };
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4565 次 |
| 最近记录: |