使用React路由器的服务器端身份验证流程

时间:2015-10-27 00:57:12

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

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

场景:

当用户第一次到达应用程序时,我们调用String VERTEX_SHADER路由器方法以检查是否存在任何当前用户(onEnter),如果他们是,我们将其重定向到他们的仪表板,否则我们会将它们重定向到目标网页。

因此,当我的应用程序点击受保护的路由localStorage时,理想情况下应该会发生什么:

onEnter

这里的问题是因为我们正在渲染服务器端,所以我们无法访问诸如onEnter: () => { if (localStorage.getItem('authToken')) { // Authenticate and redirect user to intended path } else { // Redirect the user to the login page } } 之类的内容。任何人都可以提出一种方法来克服这种情况,或者使用React Router处理服务器端身份验证的更好方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用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'

之类的内容
相关问题