代码之家  ›  专栏  ›  技术社区  ›  Shawn

响应、保持redux状态或通过jwt重新验证以保持用户登录?

  •  1
  • Shawn  · 技术社区  · 8 年前

    我想确保这个过程是一个良好的实践,如果不是,我该如何改进它?因此,我的场景是用户登录到网站并返回成功的登录响应后,我将访问令牌和刷新令牌存储在本地存储客户机端。存储完令牌后,我想调用一个操作创建者来设置我的auth reducer,使其为真。

    选项1,如果用户关闭浏览器并在访问令牌未过期时返回,我希望重新验证该用户并自动登录该用户。

    选项2,我正在考虑使用一个像redux persiste这样的包,并将保持我的auth redux状态,但是如果令牌无效,我将不得不在某个时刻使身份验证失败,然后将reducer状态设置回未经身份验证。

    希望听到其他人对他们如何在包含React、Redux和JWT的环境中处理这种情况的洞察。

    所以在我的app.jsx中,我有如下的东西:

    class App extends Component {
        componentDidMount() {
            const accessToken = localStorage.getItem('access_token');
            if (accessToken !== null) {
                //Here I would make some API call with either the access or refresh token
                //And if it's valid I would set the auth reducer to isAuthenticated.  Or I could
                //just check for the existance of the local storage item and set it the
                //reducer to isAuthenticated = true, do either of these make sense to do?
            }
        }
        render() {
            return (
                <Router>
                    <NavMenu>
                        <Switch>
                            <Route exact path='/' component={ Home }/>
                            <Route exact path='*' component={ NotFound } />
                        </Switch>
                    </NavMenu>
                </Router>
            );
        }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Subhanshu    8 年前

    最好检查令牌是否有效,而不是检查 if(token)//Logged in status:401

    如果API返回数据,则可以设置Reducer状态 isAuthenticated : true <Redirect to="/"> isAutheticated : false

        2
  •  0
  •   Dhaval Chheda    8 年前

    以下是我为我的项目所做的工作

    const auth = {
      isAuthenticated: false,
      authenticate: function() {
        if (cookie.load('token')) {
            this.isAuthenticated = true
        }
        return this.isAuthenticated;
      },
    
      signout: function() {
        cookie.remove('token', { path: '/' })
        this.isAuthenticated = false
        location.reload();
      },
    
    }
    

    通过使用 auth.authenticate()

    const PrivateRoute = ({ component: Component, ...rest }) => (
        <Route {...rest} render={props =>
            auth.authenticate()
            ? <Component {...props} /> 
            : <Redirect to={{ pathname: "/login", state: { from: props.location } }}/>
          }
        />
      );