来自 React App 的 API 用户身份验证 [英] User Authentication for API from React App

查看:46
本文介绍了来自 React App 的 API 用户身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Nodal 中内置了一个简单的 API,它允许用户创建一个新工作(本质上是服务业务的工作订单).API 使用 OAuth,因此为了创建新作业,用户必须首先通过用户名和密码进行身份验证来获取令牌.

前端将在 React 中构建.为了访问该站点,用户必须使用他们的用户名和密码登录,此时他们将获得一个令牌以进行 API 调用.两个问题:

1) 如何安全地存储 API 令牌,以便用户不必在每次页面刷新时登录?

2) 我如何使用相同的登录步骤来确定他们是否有权访问前端应用中的任何给定页面?

解决方案

这是我在当前项目中使用的流程.当用户登录时,我获取令牌并存储在 localStorage 中.然后每次用户访问任何路由时,我都会将路由服务的组件包装在一个 hoc 中.这是检查令牌的 HOC 的代码.

导出函数 requireAuthentication(Component) {类 AuthenticatedComponent 扩展 React.Component {组件WillMount(){this.checkAuth(this.props.user.isAuthenticated);}componentWillReceiveProps (nextProps) {this.checkAuth(nextProps.user.isAuthenticated);}checkAuth (isAuthenticated) {如果 (!isAuthenticated) {让redirectAfterLogin = this.props.location.pathname;browserHistory.push(`/login?next=${redirectAfterLogin}`);}}使成为 () {返回 (<div>{this.props.user.isAuthenticated === true?<组件{...this.props}/>: 空值}

)}}const mapStateToProps = (状态) =>({用户:state.user});返回连接(mapStateToProps)(AuthenticatedComponent);}

然后在我的 index.js 中,我用这个 HOC 包裹每个受保护的路由,如下所示:

这就是用户 reducer 的样子.

导出默认函数 userReducer(state = {}, action) {开关(动作.类型){案例类型.USER_LOGIN_SUCCESS:返回 {...action.user, isAuthenticated: true};默认:返回状态;}}

action.user 包含令牌.令牌可以来自用户首次登录时的 api,也可以来自 localstorage(如果该用户已经是登录用户).

I have a simple API built in Nodal which allows a user to create a new job (essentially a work order for a service business). The API is using OAuth, so in order to create a new job, the user has to first obtain a token by authenticating via username and password.

The frontend is going to be built in React. In order to access the site, the user will have to log in with their username and password, at which point they'll be given a token to make API calls. Two questions:

1) How do I securely store the API token such that the user doesn't have to log in every time the page refreshes?

2) How do I use this same login step to determine if they have access to any given page within the frontend app?

解决方案

This is the process I have used in my current project. When a user logs in, I take the token and store in localStorage. Then every time a user goes to any route, I wrap the component that the route serves in a hoc. Here is the code for the HOC that checks for token.

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

Then in my index.js I wrap each protected route with this HOC like so:

<Route path='/protected' component={requireAuthentication(ProtectedComponent)} />

This is how the user reducer looks.

export default function userReducer(state = {}, action) {
    switch(action.type) {
        case types.USER_LOGIN_SUCCESS:
            return {...action.user, isAuthenticated: true};
        default:
            return state;
    }
}

action.user contains the token. The token can either come from the api when a user first logs in, or from localstorage if this user is already a logged in user.

这篇关于来自 React App 的 API 用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆