如何在我的反应应用程序中实现 jwt 验证



我是这个项目的新手,我不明白如何在我的反应应用程序中实现 jwt auth。当我刷新页面时,每次都会丢失会话。我已经将令牌保存在本地存储中,但我不会低估我打算检查它以进行身份验证的地方。这是一些我认为可能相关的代码

路线.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)

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)
}

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

最新更新