使用 Firebase 身份验证保护 NextJS 中的路由

wal*_*per 8 firebase-authentication next.js

我要保护的路线: /account

如果用户未通过身份验证,则重定向到 /signIn

拥有 SSR NextJS 项目并使用 Firebase 身份验证,我如何才能实现经过生产实战测试的正确保护路由?

NextJS 文档中提供的示例现在无法正常工作: with-firebase-auth

所以我提交了一个问题: with-firebase-auth-example-not-working

再加上我是 NextJs 的新手,不幸的是,我从未使用过 JWT :( 或任何类型的后端保护路由 cookie/JWT/sessions 实现......直到现在我想要/需要它。

我尝试过什么样的解决方法,嗯,像这样:

import Account from "./Account.js";
import Loading from "./Loading.js";
import { useRequireAuth } from "./use-require-auth.js";

function Account(props) {
  const auth = useRequireAuth();

  // If auth is null (still fetching data) 
  // or false (logged out, above hook will redirect)
  // then show loading indicator.
  if (!auth) {
    return <Loading />;
  }

  return (
    <Account auth={auth} />
  );
}

// Hook (use-require-auth.js)
import { useEffect } from "react";
import { useAuth } from "./use-auth.js";
import { useRouter } from "./use-router.js";

function useRequireAuth(redirectUrl = '/sigIn'){
  const auth = useAuth();
  const router = useRouter();

  // If auth.user is false that means we're not
  // logged in and should redirect.
  useEffect(() => {
    if (auth.user === false){
      router.push(redirectUrl);
    }
  }, [auth, router]);

  return auth;
}
Run Code Online (Sandbox Code Playgroud)

但这一切都发生在客户端......服务器没有检查任何东西。

Ahm*_*ler 0

我将对此发布一个非常基本的答案。我不知道你将如何检查用户是否在 firebase 上进行了身份验证。我自己的代码使用 AWS Cognito 来实现此目的。

我们将把这段代码放在页面的末尾。通过这样做,如果用户未经过身份验证,我们会将用户重定向到登录页面。

export async function isAuthenticated(context) {
   // your code to check firebase authentication
   // return true if not authenticated, else return false
   
   // Maybe this way
   var user = firebase.auth().currentUser;

   if (user)
     return false;
   else 
     return true;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  let shouldRedirect = await isAuthenticated(ctx);

  if (shouldRedirect) {
    return {
      redirect: {
        destination: '/sign-in',
        permanent: false
      }
    }
  }
  return {
    props: {}
  }
}

export default Account;
Run Code Online (Sandbox Code Playgroud)

就是这样。现在该路由已通过 SSR 进行保护。