问题
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