当前位置: 首页 > 知识库问答 >
问题:

如何传递“已验证”以允许“经过身份验证的组件路由到受保护的路由”?

池宸
2023-03-14

我正在react路由器v4上实现受保护的路由。我试图将“isAuthenticated”值从“Login”组件传递到“Authenticated”组件,但得到“false”值。

也许我用错了方法,任何人都可以帮助解决这个问题吗?

我的代码如下:

登录。js提供“isAuthenticated”控件

import React, { Component } from 'react';
import { AUTH_TOKEN } from '../constants';
import { USERNAME } from '../constants';
import { graphql, compose } from 'react-apollo';
import { Row, Col, FormGroup, ControlLabel, Button } from 'react-bootstrap';
import gql from 'graphql-tag';

export const Auth = {
    isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    // setTimeout(cb, 100);
  },
  signout(cb) {
    this.isAuthenticated = false;
    // setTimeout(cb, 100);
  }
};

class Login extends Component {
  state = {
    username: '',
    password: '',
  };

    login = () => {
        Auth.authenticate();
        console.log(Auth.isAuthenticated);
    };

  render() {

    return (
      <Row>
        <Col xs={12} sm={6} md={5} lg={4}>
                    <div className="Login">
                <h4 className="page-header">Login</h4>
                  <form ref={form => (this.form = form)} onSubmit={event => event.preventDefault()}>
                    <FormGroup>
                        <ControlLabel>Username</ControlLabel>
                        <br />
                    <input
                            value={this.state.username}
                            onChange={e => this.setState({ username: e.target.value })}
                          type="text"
                          autoFocus
                      />
                    </FormGroup>

                    <FormGroup>
                        <ControlLabel>Password</ControlLabel>
                        <br/>
                        <input
                            value={this.state.password}
                        onChange={e => this.setState({ password: e.target.value })}
                            type="password"
                          />
                        </FormGroup>
                      <div onClick={() => {this._confirm(); this.login(); }}>
                          <Button type="submit" bsStyle="success">Login</Button>
                      </div>
                    </form>
                </div>
            </Col>
        </Row>
  )
};

  _confirm = async () => {
    const { username, password } = this.state;

      const result = await this.props.loginMutation({
        variables: {
          username,
          password,
        },
      });

      const { token } = result;
      this._saveUserData(token, username);

        this.props.history.push(`/`);
  }

  _saveUserData = (token, username) => {
    localStorage.setItem(AUTH_TOKEN, token);
    localStorage.setItem(USERNAME, username);
  }
};

const LOGIN_MUTATION = gql`
  mutation LoginMutation($username: String!, $password: String!) {
    loginMutation(username: $username, password: $password) {
      token
    }
  }
`;

export default compose(
  graphql(LOGIN_MUTATION, { name: 'loginMutation' }),
)(Login);

Authenticated.js需要获得“isAuthenticated”值(true)来呈现受保护的路由。

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

console.log(Auth.isAuthenticated);

class Authenticated extends Component {
  render() {
        const {
            component: Component, exact, ...rest
        } = this.props;

        return (
        <Route
            {...rest}
            exact={exact}
            render={props => (
            Auth.isAuthenticated ? (
                <Component { ...props} />
            ) : (
                <Redirect to="/login" />
        ))}
        />
        );
    }
}



export default Authenticated;

===解决方法===

Authenticated.js -

import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AUTH_TOKEN, IS_AUTHEN } from '../constants';

class Authenticated extends Component {


  render() {
        const {
            component: Component, exact, ...rest
        } = this.props;
        const isAuthenticated = !!localStorage.getItem(IS_AUTHEN) && !!localStorage.getItem(AUTH_TOKEN);
        console.log(isAuthenticated);

        return (
        <Route
            {...rest}
            exact={exact}
            render={props => (
            isAuthenticated ? (
                <Component { ...props} />
            ) : (
                <Redirect to="/login" />
        ))}
        />
        );
    }
}



export default Authenticated;

登录.js -

import React, { Component } from 'react';
import { AUTH_TOKEN, USERNAME, IS_AUTHEN } from '../constants';
import { graphql, compose } from 'react-apollo';
import { Row, Col, FormGroup, ControlLabel, Button } from 'react-bootstrap';
import gql from 'graphql-tag';

class Login extends Component {
  state = {
    username: '',
    password: '',
    authenticated: false,
  };

  render() {

    return (
      <Row>
        <Col xs={12} sm={6} md={5} lg={4}>
                    <div className="Login">
                <h4 className="page-header">Login</h4>
                  <form ref={form => (this.form = form)} onSubmit={event => event.preventDefault()}>
                    <FormGroup>
                        <ControlLabel>Username</ControlLabel>
                        <br />
                    <input
                            value={this.state.username}
                            onChange={e => this.setState({ username: e.target.value })}
                          type="text"
                          autoFocus
                      />
                    </FormGroup>

                    <FormGroup>
                        <ControlLabel>Password</ControlLabel>
                        <br/>
                        <input
                            value={this.state.password}
                        onChange={e => this.setState({ password: e.target.value })}
                            type="password"
                          />
                        </FormGroup>
                      <div onClick={() => this._confirm()}>
                          <Button type="submit" bsStyle="success">Login</Button>
                      </div>
                    </form>
                </div>
            </Col>
        </Row>
  )
};

  _confirm = async () => {
    const { username, password } = this.state;

      const result = await this.props.loginMutation({
        variables: {
          username,
          password,
        },
      });

      this.setState({ authenticated: true });
      const { token } = result;
      this._saveUserData(token, username, this.state.authenticated);

        this.props.history.push(`/channel`);
  }

  _saveUserData = (token, username, authenticated) => {
    localStorage.setItem(AUTH_TOKEN, token);
    localStorage.setItem(USERNAME, username);
    localStorage.setItem(IS_AUTHEN, authenticated);
  }
};

const LOGIN_MUTATION = gql`
  mutation LoginMutation($username: String!, $password: String!) {
    loginMutation(username: $username, password: $password) {
      token
    }
  }
`;

export default compose(
  graphql(LOGIN_MUTATION, { name: 'loginMutation' }),
)(Login);

共有1个答案

宰父飞翼
2023-03-14

首先,在应用程序(index.js)的开头,我检查令牌并将is_auth设置为我的状态,如下所示

<!-- ls is LocalStorageService for get and set from localStorage-->

    if (ls.getUserDetails() && ls.getUserDetails().roles && ls.getUserDetails().roles.length) {
      store.dispatch({ type: SET_USER_ROLE, role: ls.getUserDetails().roles[0] });
      if (ls.getToken()) {
        store.dispatch({ type: AUTHENTICATE_USER, auth: true });
      }
    }
    else {
      store.dispatch({ type: AUTHENTICATE_USER, auth: false });
    }

然后,我制作了一个AuthGuard来验证登录状态,(通过将状态的授权映射到该类的道具)

身份验证.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux'
import { store } from '../stores/configureStore';

export default function (ComposedComponent) {

    // If user not authenticated render out to root

    class AuthGuard extends Component {
        static contextTypes = {
            router: React.PropTypes.object.isRequired
        };

        componentWillMount() {
            if (!this.props.authenticated) {
                //hashHistory.push('#/login');
                store.dispatch(push('/login'));
            }
        }

        componentWillUpdate(nextProps) {
            if (!nextProps.authenticated) {
                //hashHistory.push('#/login');
                store.dispatch(push('/login'));
            }
        }

        render() {
            return <ComposedComponent {...this.props} />;
        }
    }

    const mapStateToProps = (state) => ({
        authenticated: state.auth.auth
    });

    return connect(mapStateToProps)(AuthGuard);
}

然后在我的应用程序中.js,在那里我做我的路由,

应用.js

<!--PROTECTED ROUTES GO AFTER '/app/'-->
        <Route path={`${match.url}app`} component={authGuard(MainApp)} /> 

<!--UNPROTECTED ROUTES GO AFTER '/' LIKE BELOW-->
        <Route exact path="/404" component={Page404} />
        <Route exact path="/403" component={Page403} />
        <Route exact path="/500" component={Page500} />
        <Route exact path="/confirm-email" component={PageConfirmEmail} />
        <Route exact path="/forgot-password" component={PageForgotPassword} />
        <Route exact path="/fullscreen" component={PageFullscreen} />
        <Route exact path="/lock-screen" component={PageLockScreen} />
        <Route exact path="/login" component={PageLogin} />
        <Route exact path="/sign-up" component={PageSignUp} />

在下面发表评论,:)

 类似资料:
  • 根据React Router给出的示例,我正在尝试创建一个受保护的路由,当用户未被授权使用Find Router for Relay Modern时,该路由将重定向到: 我用真实的登录逻辑替换了fakeAuth,但其余的都是一样的。这条路线就是不渲染。 发现路由器似乎是轻的例子围绕这个特定的问题。有什么想法吗?

  • 我试图实现身份验证的路由,但发现React路由器4现在阻止此工作: 错误是: 警告:您不应使用

  • Flatter Web(Navigator 2.0/Router API):如何处理经过身份验证的路由及其成功身份验证后的重定向? e、 g.我的系统中有这种路由 若用户直接打开这个URL,我想让用户先登录,那个么路由将被重定向到。。 一旦登录,我想用户导航以前打开的网址,如果有任何其他主页。。 似乎这种事情可能会有所帮助,任何想法——我们如何才能实现类似的事情?https://stackover

  • 最近我开始使用Laravel5.3来写博客,但是在运行

  • 问题内容: 我试图实现经过身份验证的路由,但是发现React Router 4现在阻止了它的工作: 错误是: 警告:您不应使用和在同一路线上;将被忽略 在这种情况下,实现此目标的正确方法是什么? 它出现在(v4)文档中,提示类似 但是在将一堆路线组合在一起时是否有可能实现这一目标? 更新 好吧,经过一番研究,我想到了这个: 发出错误的动作是正确的感觉。似乎确实不正确,还是带有其他挂钩? 问题答案:

  • 根据这个例子,我试图在React路由器v4中创建一个经过身份验证的路由。为后代显示代码: 我的身份验证状态()在减速器中初始化为空对象,它来源于Redux存储。这就是我的pp.js的样子: 问题是状态以未定义的方式开始,然后,一旦安装了路由器组件,它将状态更新为。然而,这有点晚了,因为用户已经被重定向回登录页面。我还尝试用替换生命周期方法,但这也没有解决问题。 你有什么建议? 更新1:我解决这个问