使用Reactn和Typescript的私有路由身份验证

时间:2020-11-08 18:24:06

标签: reactjs typescript google-login

我被困在实现私有路由的部分中

这就是我最终要实现的目标:

我想用Google登录,登录后我想进入一个私人路线页面,如果我退出了,那我就不能这样做。

对于代码部分:

一个用于跟踪登录状态(真/假)的类:

class Auth {
    isAuthenticated: boolean
    constructor(){
        this.isAuthenticated = false;
    }

login(){
    this.isAuthenticated= true;
}

logout(){
    this.isAuthenticated = false;
}

isLoggedIn(){
    return this.isAuthenticated;
}

}

export default new Auth();

有关Google登录名的摘要:

import React, { Component } from 'react';
import { GoogleLogin, GoogleLogout} from 'react-google-login'; 
import auth from './auth';

 login (response: any) {

   if(response.accessToken){
     this.setState(state => ({
       isLogined: true,
       userName: response.profileObj.givenName + ' ' + response.profileObj.familyName
     }));
     this.refreshTokenSetup(response);
     auth.login();
   }

 }

render() { //this is what is rendered (what users see) in the react web app pahge
   return (
   <div>
    <GoogleLogin
         clientId={ CLIENT_ID } 
         buttonText='Login' 
         onSuccess={ this.login} 
         isSignedIn={true}
         onFailure={ this.handleLoginFailure }
         cookiePolicy={ 'single_host_origin' }
         responseType='code,token' 
       />
     }

最后,我的受保护路线:

import * as React from 'react';
import {Route, Router, Redirect, RouteProps} from 'react-router-dom';
import auth from './auth';

const ProtectedRoute: React.FC<RouteProps> = ({component: Component, ...rest}) => {
    if (!Component) return null;
    return (
        <div>
            <Route {...rest} render={props => (
                auth.isAuthenticated ?
                <Component {...props} />: 
                <Redirect to="/" />
            )} />
        </div>
    );
};

export default ProtectedRoute;

根据我所遵循的教程,如果他们在ClassX中设置this.isAuthenticated=true,则在他们导入auth并在ClassA中访问它时该值仍然为true,所以我不知道如何,因为我假设每个实例都创建了新实例他们什么时候导入?

我的问题是:是否可以在一个类中将值编辑为“ true”,然后从另一个类中访问它?

如果没有,关于如何解决问题的任何建议?

0 个答案:

没有答案