如何使用Firebase身份验证来限制对next.js页面的访问? [英] How to restrict access to pages in next.js using firebase auth?

查看:126
本文介绍了如何使用Firebase身份验证来限制对next.js页面的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a next.js app which uses firebase. I need to use firebase auth package to restrict access to pages. The with-firebase-authentication example doesn't show authentication for multiple pages.

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;

推荐答案

这是

This is a React Firebase Authentication example, but it should work with next.js as well.

主要思想是创建一个高级组件,该组件检查用户是否已通过身份验证,并将所有页面包装在该组件周围:

The main idea is to create a Higher Order Component, which checks if the user is authenticated and wrap all pages around that:

import React from 'react';

const withAuthentication = Component => {
  class WithAuthentication extends React.Component {
    render() {
      return <Component {...this.props} />;
    }
  }

  return WithAuthentication;
};

export default withAuthentication;

您可以覆盖_app.js,并且仅在用户通过身份验证后才返回<Component {...pageProps} />.

You could override the _app.js and only return <Component {...pageProps} /> if the user is authenticated.

您可以执行以下操作:

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

最好是在服务器上进行处理.

Best would be to handle this on the server.

这篇关于如何使用Firebase身份验证来限制对next.js页面的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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