如何使用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.