簡體   English   中英

如何使用 getServerSideProps 使用 next-iron-session 實現身份驗證,而不在每個頁面上包含相同的代碼

[英]How can I implement authentication with next-iron-session using getServerSideProps without including the same code on each page

我正在使用next-iron-session在我的 NextJS 應用程序中實現身份驗證,目前正在使用getServerSideProps方法,它工作正常,但我必須在我想要對用戶進行身份驗證的每個頁面中實現它。 我只想以 HOC 格式或包裝格式實現它,所以我不必在每個文件中重寫它。 我為此使用以下代碼


import { withIronSession } from "next-iron-session";

const user_home = (props) => {
  if (!user.isAuth) {
    router.push("/");
  }
  // ...some other layout stuff
};
export const getServerSideProps = withIronSession(
  async ({ req, res }) => {
    const user = req.session.get("user");
    if (!user) {
      return {
        props: { isAuth: false },
      };
    }
    return {
      props: { isAuth: true, user: user },
    };
  },
  {
    cookieName: "NEXT_EXAMPLE",
    cookieOptions: {
      secure: true,
    },
    password: process.env.APPLICATION_SECRET,
  }
);

export default user_home;

這篇文章有點老了,但這是我的解決方案,因為next-iron-session已被棄用,所以使用熨斗會話。

像這樣創建一個 HOC

import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "./session";

const WithAuth = (gssp) =>
  withIronSessionSsr(async function (context) {
    const user = context.req.session.user;
    // you can check the user in your DB here 
    if (!user) {       
     return {
       redirect: {
         permanent: false,
         destination: "/login",
       },
     }
   }

   return await gssp(context);   
  }, sessionOptions);

export default WithAuth;

然后在你的頁面

export const getServerSideProps = WithAuth(async function (context) {
  ...
  return {
    props: { user: context.req.session.user, ... },
  };
});

我認為您可以從服務器重定向。

import { withIronSession } from "next-iron-session";

const user_home = (props) => {
 
  // ...some other layout stuff
};
export const getServerSideProps = withIronSession(
  async ({ req, res }) => {
    const user = req.session.get("user");
    if (!user) {
      redirect: {
        permanent: false,
        destination: "/login",
      },
    }
    return {
      props: { user: user },
    };
  },
  {
    cookieName: "NEXT_EXAMPLE",
    cookieOptions: {
      secure: true,
    },
    password: process.env.APPLICATION_SECRET,
  }
);

export default user_home;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM