Next.js使用JWT进行身份验证

我正在将一个项目从 React 转移到 Next.js 并且想知道相同的身份验证过程是否可以。基本上,用户输入他们的用户名和密码,然后通过 API (Node.js/Express) 对照数据库凭据进行检查。因此,我没有使用 Next.js 内部 api 功能,而是使用与我的 Next.js 项目完全分离的 API。

如果登录凭据正确,则会将 JWT 令牌发送回客户端。我想将其存储在本地存储中,然后重定向用户。任何未来的 http 请求都将在标头中发送令牌并通过 API 检查它是否有效。这样做可以吗?我问是因为我看到很多 Next.js auth 使用 cookie 或会话,但不知道这是否是我应该采用的“标准”方法。

回答

我的回答纯粹是基于我的经历和我读过的东西。如果我碰巧错了,请随时纠正它。

因此,我的方法是将您的令牌存储在HttpOnlycookie 中,并始终使用该 cookie 通过Authorization标头授权您对 Node API 的请求。我碰巧也在自己的项目中使用了 Node.js API,所以我知道发生了什么。

以下是我通常如何使用 Next.js 和 Node.js API 处理身份验证的示例。

为了缓解身份验证问题,我在页面中使用 Next.js 的内置getServerSideProps函数来构建一个新的可重用高阶组件来处理身份验证。在这种情况下,我将其命名为isLoggedIn

// isLoggedIn.jsx

export default (GetServerSidePropsFunction) => async (ctx) => {
  // 1. Check if there is a token in cookies. Let's assume that your JWT is stored in 'jwt'.
  const token = ctx.req.cookies?.jwt || null;

  // 2. Perform an authorized HTTP GET request to the private API to check if the user is genuine.
  const { data } = await authenticate(...); // your code here...

  // 3. If there is no user, or the user is not authenticated, then redirect to homepage.
  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }

  // 4. Return your usual 'GetServerSideProps' function.
  return await GetServerSidePropsFunction(ctx);
};

getServerSideProps 将阻止渲染,直到函数被解析,因此请确保您的身份验证快速且不会浪费太多时间。

您可以像这样使用高阶组件。让我们称这个为一个profile.jsx,作为一个人的个人资料页面。

// profile.jsx

export default isLoggedIn(async (ctx) => {
  // In this component, do anything with the authorized user. Maybe getting his data?
  const token = ctx.req.cookies.jwt;
  const { data } = await getUserData(...); // don't forget to pass his token in 'Authorization' header.

  return {
    props: {
      data,
    },
  },
});

这应该是安全的,因为几乎不可能操纵服务器端的任何内容,除非有人设法找到侵入您的后端的方法。

如果你想做一个POST请求,那么我通常是这样做的。

// profile.jsx

const handleEditProfile = async (e) => {
  const apiResponse = await axios.post(API_URL, data, { withCredentials: true });
  
  // do anything...
};

在 POST 请求中,HttpOnlycookie 也会被发送到服务器,因为withCredentials参数设置为 true。

还有一种使用 Next.js 的无服务器 API 将数据发送到服务器的替代方法。您将向“代理”Next.js 的无服务器 API 发出 POST 请求,而不是向 API 发出 POST 请求,在那里它将向您的 API 执行另一个 POST 请求。


以上是Next.js使用JWT进行身份验证的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>