【问题标题】:How can i implement jwt validation in my react app我如何在我的反应应用程序中实现 jwt 验证
【发布时间】:2023-04-07 01:52:01
【问题描述】:

我是这个项目的新手,我不明白如何在我的 react 应用程序中实现 jwt auth。当我刷新我的页面时,我每次都会失去我的会话。我已将令牌保存在本地存储中,但我不明白我应该在哪里检查身份验证。这是我认为可能相关的一些代码

routes.js

export default (
<Route path='/' component={App}>
<IndexRedirect to='/in'/>
<Route path='in' component={Authentication(MainPage)}>
  <Route path='welcome' component={Welcome}/>
  <Route path='faq' component={Faq}/>
  <Route path='update_password/:token' component={UpdatePassword}/>
  <Route path='register_data_files' component={DataFileManagement}/>
  <Route path='manage_users' component={User}/>
  <Route path='user_access_logs' component={Logs}/>
  <Route path='flat_file' component={FlatFile}/>
  <Route path='edit_user' component={EditUser}/>
  <Route path='quick_reports' component={QuickReports}/>
  <Route path='*' component={NotFound}/>
</Route>
<Route path='faq' component={LoginBar}/>
<Route path='forgot_password' component={ForgotPassword}/>
<Route path='login' component={LoginPage}/>
<Route path='update_password/:token' component={UpdatePassword}/>
<Route path='*' component={NotFound}/>

)

mainPage.jsx

const MainPage = props => (
  <div className='app-container'>
    <ApplicationBar
      actions={props.actions}
      token={props.token}
      ui={props.ui}
      user={props.user}
    />
    {React.cloneElement(props.children, props)}
  </div>
)


MainPage.propTypes = {
  actions: PropTypes.object.isRequired,
  token: PropTypes.string.isRequired,
  user: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  token: state.token,
  user: state.user,
  ui: state.ui
})
const mapDispatchToProps = dispatch => ({ actions: 
bindActionCreators(actions, dispatch) })

export default connect(mapStateToProps, mapDispatchToProps)(MainPage)

authentication.jsx

export default function (Component) {
  class Authentication extends Component {
    componentWillMount() {
      this.pushToLoginIfNotAuthenticated(this.props.auth)
}

componentWillReceiveProps({auth}) {
  this.pushToLoginIfNotAuthenticated(auth)
}

pushToLoginIfNotAuthenticated(auth) {
  !auth && this.store.dispatch(push('/login'))
}

    render() {
      return this.props.auth && <Component {...this.props} />
    }
  }

  const mapStateToProps = state => ({ auth: true })
  const mapDispatchToProps = dispatch => ({ push: 
bindActionCreators(push, 
dispatch) })

  return connect(mapStateToProps, mapDispatchToProps)(Authentication)
}

【问题讨论】:

    标签: javascript reactjs redux jwt token


    【解决方案1】:

    在您的应用程序启动之前,您应该检查 localStorage 是否有令牌,如果它不为空,请调度一个操作,以便您可以在您的状态上设置它。我通常在设置我的 redux 商店后这样做。如果您需要一些代码示例,请告诉我,我会在此处添加! 再见!

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 2011-02-18
      • 2018-09-11
      • 2018-08-15
      • 1970-01-01
      • 2014-01-15
      • 2015-08-08
      • 1970-01-01
      相关资源
      最近更新 更多