簡體   English   中英

我如何在我的 React 應用程序中實現 jwt 驗證

[英]How can i implement jwt validation in my react app

我是這個項目的新手,我不明白如何在我的 React 應用程序中實現 jwt auth。 當我刷新頁面時,我每次都會丟失會話。 我已經將令牌保存在 localstorage 中,但我不明白我打算在哪里檢查身份驗證。 這是我認為可能相關的一些代碼

路由.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}/>

)

主頁.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)

身份驗證.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)
}

在您的應用程序啟動之前,您應該檢查 localStorage 的令牌,如果它不為空,則調度一個操作,以便您可以將其設置為您的狀態。 我通常在設置我的 redux store 后這樣做。 如果您需要一些代碼示例,請告訴我,我會在這里添加它! 再見!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM