reactjs - 使用 React Router 的服务器端身份验证流程

标签 reactjs authentication react-router url-routing isomorphic-javascript

我想知道如果我的应用程序在服务器端渲染,如何使用 React Router 准确实现身份验证流程?

场景:

当用户首次到达应用程序时,我们会调用 onEnter 路由器方法来检查当前用户是否存在 (localStorage),如果他们是我们的话将他们重定向到他们的仪表板,否则我们将他们重定向到登陆页面。

因此,当我的应用程序访问 protected 路由 onEnter 时,理想情况下应该发生以下情况:

onEnter: () => {
    if (localStorage.getItem('authToken')) {
        // Authenticate and redirect user to intended path
    } else {
        // Redirect the user to the login page
    }
}

这里的问题是,因为我们是在服务器端渲染,所以我们无法访问 localStorage 等内容。任何人都可以建议一种方法来克服这个问题,或者使用 React Router 处理服务器端身份验证的更好方法吗?

最佳答案

您可以使用context ,例如:

import React, { Component, PropTypes, Children } from 'react'

class Provider extends Component {

    static childContextTypes = {
        isAuthed: PropTypes.bool
    }

    constructor(props) {
        super(props);
        this.initialData = isClient ? window.__initialData__ : props.initialData;
    }

    getChildContext() {
        return {
            isAuthed: this.initialData.isAuthed
        };
    }

    render() {
        let { children } = this.props;
        return Children.only(children);
    }
}

并换行:

// The server creates this object:
const initialData = {
    isAuthed: true
};

if (IS_CLIENT) {
    ReactDOM.render(
        <Provider>
            <Router history={createHistory()}>{Routes}</Router>
        </Provider>,
        document.getElementById('app')
    );
}

if (IS_SERVER) {
    // Using renderToStaticMarkup/renderToString etc on:
    <Provider initialData={initialData}> 
        <RoutingContext {...renderProps} />
    </Provider>
}

然后您可以从任何组件在服务器或客户端上访问它:

import React, { Component, PropTypes } from 'react'

class SomeComponent extends Component {

    static contextTypes = {
        isAuthed: PropTypes.bool
    }

    constructor(props, context) {
        super(props, context);

        console.log(context.isAuthed); // this.context outside ctor
    }
}

简单的客户端检查类似 typeof document !== 'undefined'

关于reactjs - 使用 React Router 的服务器端身份验证流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358249/

相关文章:

ruby-on-rails - react /Rails : Append dynamically element to DOM

authentication - 与Kubernetes请求关联的UID如何使用?

reactjs - React js 错误边界不适用于 Promise Catch

javascript - 在哪里可以使用 React 中的 hooks 进行 API 调用?

reactjs - 无法获取react-hook-form中的值表单输入

java - 登录和访问类(class)?

regex - 如何在 React Router DOM 中使用正则表达式从路由匹配中排除参数?

javascript - React-router:将 props 传递给 es6 处理程序组件

javascript - 在 Click 上渲染选择标签 - REACT JS

wcf - 选择性地接受自承载 WCF 服务中的客户端证书