我有一个内置在Nodal中的简单API,它允许用户创建新作业(本质上是服务业务的工单)。该API使用的是OAuth,因此为了创建新作业,用户必须首先通过用户名和密码进行身份验证来获得令牌。
前端将在React中构建。为了访问该站点,用户将必须使用其用户名和密码登录,这时将为他们提供令牌以进行API调用。两个问题:
1)如何安全地存储API令牌,以使用户不必在每次页面刷新时都登录?
2)如何使用同一登录步骤来确定他们是否有权访问前端应用程序中的任何给定页面?
最佳答案
这是我在当前项目中使用的过程。当用户登录时,我将令牌并存储在localStorage中。然后,每次用户转到任何路线时,我都会将路线所服务的组件包装在一个临时文件中。这是用于检查令牌的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。
关于javascript - 来自React App的API用户身份验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40660745/