使用FireBase的受保护路由 [英] Protected Route With Firebase

查看:19
本文介绍了使用FireBase的受保护路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Next.js应用程序中使用Firebase进行用户身份验证。我想保护客户端的用户。我使用了Firebase Firebaseui Reaction-FirebaseUI来实现Google Auth。如何在客户端自身保护路由

  const uiConfig = {
    signInFlow: "popup",
    signInSuccessUrl: "/dashboard",
    signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
  }

我要保护仪表板路由。 提前感谢:)

推荐答案

路由器:

首先,您需要维护一个包含所有公共路由和受保护路由的路由器。


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;

受保护路由:

这是保护路径,如果应允许用户根据应用的身份验证状态访问应用上的受保护页面,则该路径将进行处理。

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;

Firebase身份验证状态:

这是用于跟踪用户登录和注销的自定义挂钩。


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 };
};

这篇关于使用FireBase的受保护路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆