How to restrict access to pages in next.js using firebase auth?

与世无争的帅哥 提交于 2020-05-13 06:36:25

问题


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;

回答1:


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;

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

You could do something like this:

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.




回答2:


Hi after some research here there seems to be two ways of doing this. Either you alternate the initialization process of the page using Custom to include authentication there - in which case you can transfer the authentication state as prop to the next page - or you would ask for a new authentication state for each page load.




回答3:


Struggled with integrating firebase auth as well, ended up using the approach detailed in the with-iron-session example on nextjs: https://github.com/hajola/with-firebase-auth-iron-session



来源:https://stackoverflow.com/questions/54522858/how-to-restrict-access-to-pages-in-next-js-using-firebase-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!