我如何在我的反应应用程序中实现 jwt 验证
Posted
技术标签:
【中文标题】我如何在我的反应应用程序中实现 jwt 验证【英文标题】:How can i implement jwt validation in my react app 【发布时间】:2019-02-28 07:15:53 【问题描述】:我是这个项目的新手,我不明白如何在我的 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】:在您的应用程序启动之前,您应该检查 localStorage 是否有令牌,如果它不为空,请调度一个操作,以便您可以在您的状态上设置它。我通常在设置我的 redux 商店后这样做。如果您需要一些代码示例,请告诉我,我会在此处添加! 再见!
【讨论】:
以上是关于我如何在我的反应应用程序中实现 jwt 验证的主要内容,如果未能解决你的问题,请参考以下文章