来自 React App 的 API 的用户身份验证
User Authentication for API from React App
我在 Nodal 中内置了一个简单的 API,允许用户创建新工作(本质上是服务业务的工作订单)。 API 使用 OAuth,因此为了创建新作业,用户必须首先通过用户名和密码进行身份验证来获取令牌。
前端将在 React 中构建。为了访问该站点,用户必须使用他们的用户名和密码登录,此时他们将获得一个令牌以进行 API 调用。两个问题:
1) 如何安全地存储 API 令牌,这样用户就不必在每次刷新页面时都登录?
2) 我如何使用相同的登录步骤来确定他们是否可以访问前端应用程序中的任何给定页面?
这是我在当前项目中使用的过程。当用户登录时,我获取令牌并存储在 localStorage 中。然后,每次用户访问任何路由时,我都会将路由服务的组件包装在一个 hoc 中。这是检查令牌的 HOC 代码。
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth(this.props.user.isAuthenticated);
}
componentWillReceiveProps (nextProps) {
this.checkAuth(nextProps.user.isAuthenticated);
}
checkAuth (isAuthenticated) {
if (!isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
browserHistory.push(`/login?next=${redirectAfterLogin}`);
}
}
render () {
return (
<div>
{this.props.user.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
user: state.user
});
return connect(mapStateToProps)(AuthenticatedComponent);
}
然后在我的 index.js 中,我用这个 HOC 包装每个受保护的路由,如下所示:
<Route path='/protected' component={requireAuthentication(ProtectedComponent)} />
这是用户减速器的样子。
export default function userReducer(state = {}, action) {
switch(action.type) {
case types.USER_LOGIN_SUCCESS:
return {...action.user, isAuthenticated: true};
default:
return state;
}
}
action.user 包含令牌。令牌可以来自用户首次登录时的 api,或者如果该用户已经是登录用户,则来自 localstorage。
我在 Nodal 中内置了一个简单的 API,允许用户创建新工作(本质上是服务业务的工作订单)。 API 使用 OAuth,因此为了创建新作业,用户必须首先通过用户名和密码进行身份验证来获取令牌。
前端将在 React 中构建。为了访问该站点,用户必须使用他们的用户名和密码登录,此时他们将获得一个令牌以进行 API 调用。两个问题:
1) 如何安全地存储 API 令牌,这样用户就不必在每次刷新页面时都登录?
2) 我如何使用相同的登录步骤来确定他们是否可以访问前端应用程序中的任何给定页面?
这是我在当前项目中使用的过程。当用户登录时,我获取令牌并存储在 localStorage 中。然后,每次用户访问任何路由时,我都会将路由服务的组件包装在一个 hoc 中。这是检查令牌的 HOC 代码。
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth(this.props.user.isAuthenticated);
}
componentWillReceiveProps (nextProps) {
this.checkAuth(nextProps.user.isAuthenticated);
}
checkAuth (isAuthenticated) {
if (!isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
browserHistory.push(`/login?next=${redirectAfterLogin}`);
}
}
render () {
return (
<div>
{this.props.user.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
user: state.user
});
return connect(mapStateToProps)(AuthenticatedComponent);
}
然后在我的 index.js 中,我用这个 HOC 包装每个受保护的路由,如下所示:
<Route path='/protected' component={requireAuthentication(ProtectedComponent)} />
这是用户减速器的样子。
export default function userReducer(state = {}, action) {
switch(action.type) {
case types.USER_LOGIN_SUCCESS:
return {...action.user, isAuthenticated: true};
default:
return state;
}
}
action.user 包含令牌。令牌可以来自用户首次登录时的 api,或者如果该用户已经是登录用户,则来自 localstorage。