next.js 使用Cookie的JWT身份验证NestJS(应用程序路由器)

lxkprmvk  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(144)

在项目中,我们有NestJS后端和NextJS框架的前端部分。后端逻辑:
1.在身份验证请求后将auth-cookie设置为httpOnly cookie。
1.检查auth-cookie是否为Guarded请求。
后端部分工作正常,并已使用Postman(localhost:4000)进行了测试。我们实现了端点,以便能够在代理服务器逻辑的帮助下在与NextJS相同的端口上进行本地调用(localhost:3000/api用于后端调用)。
例如,现在我们可以在http://localhost:3000/api/login上对同一个NextJS服务器进行身份验证POST,而不是从客户端应用程序访问后端服务器。我们希望在NextJS服务器收到来自POST localhost:4000/auth/login的响应后立即设置cookie。从而客户端不直接与后端相关。

如何在客户端存储这些cookie或将来重用它们?

src\app\API\login\route.ts

import { _POST } from "@/providers/POST";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest, response: NextResponse) {
  return _POST(request, "/auth/login");
}

这是具有email + password凭据的:3000/api/login的路由。

src\providers\POST.ts

import axios from "axios";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

export const _POST = async (request: NextRequest, url: string) => {
    /* 
        some configs 
    */
    
    let config = {
      method: "post",
      maxBodyLength: Infinity,
      url: backendURL + url,
      headers: {
        "Content-Type": "application/json",
     },
      data: data,
    };
    return axios
      .request(config)
      .then((response) => {
        const cookieStore = cookies();
        const tokenCookie = cookieStore.get("auth-cookie");
        console.log("tokenCookie", tokenCookie); // tokenCookie undefined
        console.log(JSON.stringify(response.data)); // successful authorization
        return NextResponse.json(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }
};
wyyhbhjk

wyyhbhjk1#

不确定您是如何设置Set-Cookie响应头的,但这可能是由于未配置Path属性。
你试过这个吗?
在成功登录服务器后,它看起来像这样:

return new Response('Success', {
 status: 200,
 headers: {
  'Set-Cookie': `token=${YOUR_TOKEN}; HttpOnly; Path=/`,
 },
})

希望这能帮上忙。

相关问题