【问题标题】:How to restrict access to pages in next.js using firebase auth?如何使用firebase auth限制对next.js中页面的访问?
【发布时间】:2019-06-28 14:09:44
【问题描述】:

我正在开发一个使用 firebase 的 next.js 应用程序。我需要使用 firebase auth 包来限制对页面的访问。 with-firebase-authentication 示例不显示多个页面的身份验证。

import React from 'react';
import Router from 'next/router';

import { firebase } from '../../firebase';
import * as routes from '../../constants/routes';

const withAuthorization = (needsAuthorization) => (Component) => {
  class WithAuthorization extends React.Component {
    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        if (!authUser && needsAuthorization) {
          Router.push(routes.SIGN_IN)
        }
      });
    }

    render() {
      return (
        <Component { ...this.props } />
      );
    }
  }

  return WithAuthorization;
}

export default withAuthorization;

【问题讨论】:

    标签: firebase firebase-authentication next.js


    【解决方案1】:

    嗨,经过一些研究here 似乎有两种方法可以做到这一点。您可以使用Custom 交替页面的初始化过程以在其中包含身份验证 - 在这种情况下,您可以将身份验证状态作为道具传输到下一页 - 或者您会为每个页面加载请求新的身份验证状态。

    【讨论】:

      【解决方案2】:

      这是一个React Firebase Authentication 示例,但它也应该适用于next.js

      主要思想是创建一个高阶组件,它会检查用户是否通过了身份验证并将所有页面都包裹起来:

      import React from 'react';
      
      const withAuthentication = Component => {
        class WithAuthentication extends React.Component {
          render() {
            return <Component {...this.props} />;
          }
        }
      
        return WithAuthentication;
      };
      
      export default withAuthentication;
      

      您可以覆盖_app.js,并且仅在用户通过身份验证时返回&lt;Component {...pageProps} /&gt;

      你可以这样做:

      const withAuthorization = (needsAuthorization) => (Component) => {
        class WithAuthorization extends React.Component {
          state = { authenticated: null }
          componentDidMount() {
            firebase.auth.onAuthStateChanged(authUser => {
              if (!authUser && needsAuthorization) {
                Router.push(routes.SIGN_IN)
              } else {
                // authenticated
                this.setState({ authenticated: true })
              }
            });
          }
      
          render() {
            if (!this.state.authenticated) {
              return 'Loading...'
            }
            return (
              <Component { ...this.props } />
            );
          }
        }
      
        return WithAuthorization;
      }
      

      最好在服务器上处理。

      【讨论】:

      • 我已将问题修改为我找到的解决方案,但页面仅在呈现所述页面内容后才会重定向..
      • 我应该将 HOC 添加到页面组件吗????我尝试了与您在上面所做的类似的操作,但它会呈现然后重定向..
      【解决方案3】:

      也在努力集成 firebase 身份验证,最终使用 nextjs 上的 with-iron-session 示例中详述的方法:https://github.com/hajola/with-firebase-auth-iron-session

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 2014-08-24
        • 2018-06-06
        • 2012-01-02
        相关资源
        最近更新 更多