我在Koa服务器上运行ReactRouter。
配置了我的Koa服务器,以便所有请求都指向'index.html'(使用koa-connect-history-api-fallback),然后将请求转发到ReactRouter。这一切都很好,除了我在弄清楚如何进行用户身份验证时遇到麻烦。
我想保护我的路线,以便用户必须登录才能访问任何路线。问题是我的登录页面是“路线”之一,这意味着用户必须登录才能访问登录页面!
有没有解决这个问题的好方法?例如,在我的Koa服务器中,我可以某种方式保护除“ / login”路由之外的所有路由吗?我已经阅读了这个示例,该示例负责ReactRouter内的身份验证,但是对您而言,在客户端进行身份验证似乎有些粗略。我可能会不在基地。
如果您好奇,我正在研究react-redux-starter-kit
您可以使用装饰器来验证顶级组件,例如
// auth.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
export default function(ComposedComponent) {
class Auth extends Component {
static contextTypes = {
router: React.PropTypes.object
}
componentWillMount() {
if (!this.props.authenticated) {
this.context.router.push('/');
}
}
componentWillUpdate(nextProps) {
if (!nextProps.authenticated) {
this.context.router.push('/');
}
}
render() {
return <ComposedComponent {...this.props} />
}
}
function mapStateToProps(state) {
return {authenticated: state.auth.authenticated};
}
return connect(mapStateToProps)(Auth);
}
和:
@auth
...your component...
或者,如果您拥有auth模块,则可以以一种“减少冗余”的方式来实现:
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="login" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>
), document.getElementById('example'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句