来自React App的API的用户认证

User Authentication for API from React App

本文关键字:用户 认证 API 来自 App React      更新时间:2023-09-26

我在node中内置了一个简单的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;
    }
}

行动。用户包含令牌。令牌可以来自用户首次登录时的api,也可以来自本地存储(如果该用户已经登录)。