当令牌在 React 上无效时重定向到登录页面 [英] Redirect to login page when token is invalid on React

查看:44
本文介绍了当令牌在 React 上无效时重定向到登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到多个线程建议在 redux 上使用路由,但总的来说,这些示例包含一个公共主页,其中包含登录、注销、访问仪表板等选项.我正在寻找的是,如果令牌仍然有效,则允许用户访问应用程序,否则,它应该重定向到登录页面,该页面不是应用程序主要布局的一部分.让我展示一些代码:

function checkAuth() {const token = localStorage.getItem('token');如果(!令牌){返回假;}尝试 {让有效载荷 = 解码(令牌);if (payload.exp < new Date().getTime()/1000) {返回假;}}赶上(e){返回假;}返回真;}类 Main 扩展组件 {构造函数(道具){超级(道具);this.output = this.output.bind(this)this.state = { 登录:false }}输出(evt){this.setState({登录: evt})}内容({输出,登录}){如果(checkAuth())返回(<布局/>);如果(!登录)return(<登录函数={输出}/>);别的返回(<布局/>);}使成为() {返回 (<this.Content output={this.output} 登录={this.state.loggedin}/>)};}

首先,我对令牌进行了验证;如果它仍然有效,则函数内容"将返回仪表板,否则将返回登录页面.然后,我发送一个函数输出"到子组件登录",因此登录页面能够更改标志登录"的状态,此状态的更改将呈现仪表板.

我的应用组件:

class App 扩展组件 {使成为() {返回 (

<路由器><路由路径="/";组件={主}/></路由器>

)};}

它现在按预期工作,但我觉得代码逻辑可以改进.关于它的一些意见会有所帮助,我是 React 初学者.我已经在 Github 上发布了代码:完整代码

解决方案

您可以创建一个名为ProtectedRoute"的组件;在它内部执行令牌验证逻辑,如果没有令牌,它会将您重定向到登录页面

//包import React, { Fragment } from 'react';从'react-router-dom'导入{路由,重定向};const ProtectedRoute = ({ component: Component, ...rest }) =>{const checkValidToken = () =>{const token = localStorage.getItem('token');//验证逻辑...}返回 (<片段>{checkValidToken()?<Route {...rest} render={props =><组件{...rest} {...props}/>}/>:<重定向到=/auth?mode=login";/>}</片段>);}导出默认的 ProtectedRoute

然后按如下方式使用

class App 扩展组件 {使成为() {返回 (

<路由器><ProtectedRoute path="/";组件={主}/></路由器>

)};}

I have seen multiple threads that suggest the use of Routes on redux, but in general, the examples contain a public Main Page with the options to Log in, Logout, Access to Dashboard, etc. What I'm looking for is to allow the user to access the app if the token is still valid, otherwise, it should redirect to the Login page, which is not part of the main layout of the app. Let me show some code:

function checkAuth() {
      const token = localStorage.getItem('token');
      if (!token) {
        return false;
      }

      try {
        let payload = decode(token);
        if (payload.exp < new Date().getTime() / 1000) {
          return false;
        }
      } catch (e) {
        return false;
      }
      return true;
    }

    class Main extends Component {
      constructor(props) {
        super(props);
        this.output = this.output.bind(this)
        this.state = { loggedin: false }
      }
      output(evt) {
          this.setState({loggedin: evt})
      }
      Content({output, loggedin})
      {
        if (checkAuth())
          return(<Layout/>);
        if (!loggedin)
          return(<Login func={output}/>);
        else
          return(<Layout/>);
      }
      render() {
        return (
            <this.Content output={this.output} loggedin={this.state.loggedin}/>
         )
      };
    }

First, I made validation of the token; if it is still valid, the function " Content" will return the Dashboard, otherwise, it will return the Login Page. Then, I send a function "output" to the child component "Login", so the Login page is able to change the state of the flag "loggedin", the change of this state will render the dashboard.

My App component:

class App extends Component {
  render() {
    return (
      <div className="App">
          <Router>
            <Route path="/" component={Main} />
          </Router>
      </div>
     )
  };
}

It works by now as expected, but I have the feeling the code logic can be improved. It would be helpful for some opinions about it, I'm a React beginner. I have published the code on Github: Full Code

解决方案

You could create a component called "ProtectedRoute" where inside it does the token validation logic and in case there's no token, it redirects you to the login page

// Packages
import React, { Fragment } from 'react';
import { Route, Redirect } from 'react-router-dom';


const ProtectedRoute = ({ component: Component, ...rest }) => {

  const checkValidToken = () => {
    const token = localStorage.getItem('token');
    
    // Validation logic...
  }

  return (
    <Fragment>
      {checkValidToken()
          ? <Route {...rest} render={props => <Component {...rest} {...props} />} />
          : <Redirect to="/auth?mode=login" />
      }
    </Fragment>
  );
}

export default ProtectedRoute

and then use it as follow

class App extends Component {
  render() {
    return (
      <div className="App">
          <Router>
            <ProtectedRoute path="/" component={Main} />
          </Router>
      </div>
     )
  };
}

这篇关于当令牌在 React 上无效时重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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