JWT身份验证与cookies在NestJS中(应用程序路由器)

huangapple go评论48阅读模式
英文:

JWT Authentication with cookies NestJS (App Router)

问题

在项目中,我们有NestJS后端和NextJS前端框架。
后端逻辑:
1)在身份验证请求之后将auth-cookie设置为httpOnly的cookie。
2)检查auth-cookie以进行受保护的请求。

后端部分运行正常,并已使用Postman进行测试(localhost:4000)。我们实现了端点,可以在同一端口上本地调用,使用代理服务器逻辑在NextJS中(localhost:3000/api用于后端调用)。

例如,现在我们可以在http://localhost:3000/api/login上进行身份验证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");
}

这是:3000/api/login的路由,使用email + password凭据。

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) => {
    /* 
        一些配置 
    */
    
    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);
      });
  }
};

如果需要进一步的翻译或信息,请告诉我。

英文:

In the project, we have NestJS backend and NextJS frameworks for the frontend part.
Backend logic:

  1. set auth-cookie as httpOnly cookies after the authentication request.
  2. check for the auth-cookie for a Guarded request.

The backend part works fine and has been tested using Postman (localhost:4000). We implemented endpoints to be able to call locally on the same port as NextJS with the help of proxy server logic there (localhost:3000/api for backend calls).

For example, now we can make auth POST on http://localhost:3000/api/login to the same NextJS server instead of accessing the backend server from the client app. We expect cookies to be set right after NextJS server will receive response from POST localhost:4000/auth/login. So that a client is not related to the backend directly.

How to store these cookies on client side or reuse them for future?

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");
}

This is the route for :3000/api/login with email + password credentials.

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);
      });
  }
};

答案1

得分: 1

这可能是由于未配置Path属性而导致的,不确定您是如何设置Set-Cookie响应头的。

您尝试过这样吗?

在服务器成功登录后,它会看起来像这样:

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

希望这对您有帮助。

英文:

Not sure how you are setting the Set-Cookie response header but this may be due to the Path attribute not being configured.

Have you tried this?

It would look something like this after a successful login on the server:

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

Hope this helps.

huangapple
  • 本文由 发表于 2023年5月17日 20:44:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定