繁体   English   中英

使用 Firebase Auth Context 的 React-Ionic 应用程序中的受保护路由

[英]Protected Routes in React-Ionic app using Firebase Auth Context

我正在尝试在 React-Ionic 应用程序中为 Firebase 身份验证设置上下文,其中包含一些受保护的路由,未经身份验证不应访问这些路由。 到目前为止,它有点工作,但不完全。 我可以毫无问题地登录并使用受保护的路线导航页面,但是一旦我刷新页面,它就会带我回到登录页面,就好像我没有经过身份验证一样。

我很确定我在某个地方搞砸了,但无法检测到哪里(实际上整个事情可能被错误地实施,因为我对此很陌生并且仍在学习)。

这是我的文件到目前为止的样子(没有导入和东西,只是核心部分):

应用程序.tsx

const App: React.FC = () => {

  const authContext = useContext(AuthContext);

  useEffect(() => {
    console.log(authContext) **//**
  }, [])  

  return (
    <IonApp>
      <IonReactRouter>
        <IonRouterOutlet>
          <Route exact path="/" component={PageLogin} />
          <ProtectedRoute path="/secure/home" component={PageHome} isAuthenticated={authContext.authenticated!}/>
          <ProtectedRoute path="/secure/lot/:lotId" component={PageLotOverview} isAuthenticated={authContext.authenticated!}/>
          <ProtectedRoute path="/secure/shipment/:shipmentId" component={PageShipmentOverview} isAuthenticated={authContext.authenticated!}/>
        </IonRouterOutlet>
      </IonReactRouter>
    </IonApp>
  )
}

AuthProvider.tsx:

export const AuthContext = React.createContext<Partial<ContextProps>>({});

export const AuthProvider = ({ children }: any) => {

  const [user, setUser] = useState(null as firebase.User | null);
  const [loadingAuthState, setLoadingAuthState] = useState(true);

  useEffect(() => {
    firebase.auth().onAuthStateChanged((user: any) => {
      setUser(user);
      setLoadingAuthState(false);
    });
  }, []);

  return (
    <AuthContext.Provider
      value={{
        user,
        authenticated: user !== null,
        setUser,
        loadingAuthState
      }}>
      {children}
    </AuthContext.Provider>
  );
}

ProtectedRoute.tsx:

interface ProtectedRouteProps extends RouteProps {
  component: React.ComponentType<any>;
  path: string;
  isAuthenticated: boolean
}


export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ component: Component, path, isAuthenticated }) => {

  useEffect(() => {
    console.log("from protected ROUTE", isAuthenticated)
  }, [])

return (
    <Route path={path} render={() => isAuthenticated ? <Component /> : <Redirect to="/" />} />
  );
};

索引.tsx:

ReactDOM.render(
  <AuthProvider>
    <App />
  </AuthProvider>
  , document.getElementById('root'));

如果我能提供更多有用的信息,请告诉我。 在此先感谢您的帮助。

第一:每个人都还在学习

2号:我个人使用了一个非常简单的解决方案(工作正常)。 您可以使用称为“会话存储”的工具。

从 Firebase 获取用户数据后,请立即执行以下操作:


// When login is successful

window.sessionStorage.setItem('isLogged', 'true'); 

// This will create a variable with value *true* that 
can be accessed from any page within your website

会话存储就像一个本地数据库,可以存储您想要保存的任意数量的值,并且不会在刷新时被删除。 然而,它只是暂时的,当用户关闭浏览器窗口时会被删除。

现在,在每条受保护的路线上,您都可以这样做。

useEffect(() => {
  if(window.sessionStorage.getItem('isLogged') == 'false')
  {
    window.location.href = '/login' // send the user to login page
  }
}, [])

专业提示

使用可以使用此机制为您正在开发的任何内容实现“记住我”选项。 在这种情况下,您可能必须使用类似于sessionStorageLocalStorage ,但即使用户关闭浏览器窗口,它也不会删除数据。

当用户访问你的页面时,它会自动将用户重定向到主页而不登录(如果你创建了一个useEffect来检查它)。

另一件事: localStoragesessionStorage对于不同的用户是不同的。 存储在我浏览器的localStoragesessionStorage中的值将不会对您或除我之外的任何人可见。

而已

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM