【问题标题】:Authorization with respect to React Router关于 React Router 的授权
【发布时间】:2019-08-01 12:17:16
【问题描述】:

我正在尝试在前端级别实现授权,并且正在使用 react-router。我想出的代码已附在下面。我的问题是:

1.) 我们可以有条件地渲染/删除<Switch><Route>

2.) 为什么下面的代码不起作用,即使我在浏览器中点击 /user,它也会将我重定向到 /dashboard(/dashboard 是存在令牌时存储在 noMatchUrl 变量中的值,否则存储 /login)

非常感谢任何帮助

我在互联网上搜索过,但没有找到任何与我的场景几乎不相近的东西

{
    token
    ?
    <Switch>
        <Route exact path="/dashboard" component={Dashboard} />
        <Route exact path="/tasks" component={Tasks} />
        <Route exact path="/lists" component={Lists} />
        <Route exact path="/user" component={User} />
        <Route exact path="/logout" component={Logout} />
        <Route render={() => (<Redirect to={noMatchUrl} />)} />
    </Switch>
    :
    <Switch>
        <Route exact path={["/reset-password/:token", "/set-password/:token"]} component={ResetPassword} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/forgot-password" component{ForgotPassword}/>
        <Route render={() => (<Redirect to={noMatchUrl} />)} />
    </Switch>
}

我希望授权正常工作,但现在即使正常路由也无法正常工作,如上所述

【问题讨论】:

  • 它应该可以工作。你有什么错误吗?
  • 我没有收到任何错误,我只是想知道这是否是实施授权的正确方法
  • 有一个与错误路由相关的错误现已解决,所以我目前的问题与我实施授权的方式有关
  • 是的。您可以继续使用这种方法。

标签: reactjs react-router react-router-dom


【解决方案1】:

您不应该在路由器之间使用三元语句。我建议您使用某种私有路由组件,在其中检查令牌,然后在失败时返回一个组件,如果它通过或重定向,如下所示:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import Auth from '../../Modules/Auth';

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

    <Route {...rest} render={(props) => (
      Auth.isUserAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
          }} />
    )} />
  )

  export default PrivateRoute;

然后在要导入的 Auth 文件中编写一个检查令牌的类,但它可能是:

class Auth {

    /**
     * Authenticate a user. Save a token string in Local Storage
     *
     * @param {string} token
     */
    static authenticateUser(token) {
      localStorage.setItem('token', token);
    }

    /**
     * Check if a user is authenticated - check if a token is saved in Local Storage
     *
     * @returns {boolean}
     */
    static isUserAuthenticated() {
      return localStorage.getItem('token') !== null;
    }

    /**
     * Deauthenticate a user. Remove a token from Local Storage.
     *
     */
    static deauthenticateUser() {
      localStorage.removeItem('token');
    }

    /**
     * Get a token value.
     *
     * @returns {string}
     */

    static getToken() {
      return localStorage.getItem('token');
    }

  }

  export default Auth;

然后在你的 switch 中你可以写这样的东西:

<Switch>
        <PrivateRoute exact path="/dashboard" component={Dashboard} />
        <PrivateRoute exact path="/tasks" component={Tasks} />
        <PrivateRoute exact path="/lists" component={Lists} />
        <PrivateRoute exact path="/user" component={User} />
        <PrivateRoute exact path="/logout" component={Logout} />
        <Route exact path={["/reset-password/:token", "/set-password/:token"]} component={ResetPassword} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/forgot-password" component{ForgotPassword}/>
        <Route render={() => (<Redirect to={noMatchUrl} />)} />
</Switch>

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2011-10-25
    • 2020-11-21
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多