我如何在我的React App中实现jwt验证

时间:2018-09-24 18:08:03

标签: javascript reactjs redux jwt token

我是这个项目的新手,我不明白如何在我的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)
}

1 个答案:

答案 0 :(得分:0)

在应用启动之前,应检查令牌的localStorage,如果它不为null,则调度一个操作,以便可以将其设置为您的状态。我通常在设置Redux存储区后执行此操作。如果您需要一些代码示例,请告诉我,我将在此处添加! 再见!