在 Nextjs 开发服务器的 Set-Cookie 中重写域

问题描述 投票:0回答:1

我们使用 CORS + SameSite 来防止服务器端的 CSRF 攻击,Next.js 使用 Apache

mod_proxy
构建静态站点,
Domain
组件由 Apache 的
ProxyPassReverseCookieDomain
指令处理。

这种 CSRF 保护会破坏本地开发服务器。最初我们在

next.config.js
:

中配置了重写
if (process.env.BACKEND_API) {
    nextConfig.rewrites = async () => {
        return [
            {
                source: '/api/:path*',
                destination: `${process.env.BACKEND_API}/:path*`
            }
        ]
    }
}

但是现在我们需要中间件来将

Set-Cookie
Domain
从一个名称重写为
localhost
...

是否可以仅为开发服务器定义 cookie 上的中间件操作?

next.js csrf middleware setcookie http-proxy-middleware
1个回答
0
投票

这里是一个位于

src/middleware.ts
的中间件,它修改了Domain属性:

export async function middleware(request: NextRequest) {
  // Only run this middleware in development
  if (process.env.NODE_ENV !== "development") return NextResponse.next();

  // GET request to get the original headers
  const { headers } = await fetch(request);

  if (headers.has("Set-Cookie")) {
    const cookies = headers.get("Set-Cookie")!;

    // Replace the Domain attribute to localhost
    const modifiedCookies = cookies.replace(/Domain=[^;]+/, "Domain=localhost");

    // Set the modified Set-Cookie header
    headers.set("Set-Cookie", modifiedCookies);
  }

  return NextResponse.next({
    headers: headers,
  });
}

export const config = {
  matcher: "/api/:path*",
};

但是,该解决方案存在两个缺点:

  • 需要对后端进行额外的提取调用来检索 cookie。
  • 响应包含两个 Set-Cookie 标头:原始标头带有后端域,另一个带有 localhost。
© www.soinside.com 2019 - 2024. All rights reserved.