在NextJS中间件内设置仅限http的cookie

n1bvdmb6  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(151)

我正在尝试设置一个新的访问令牌时,当前一个到期内我的中间件,这样做...
1.我创建了一个新令牌
1.将它传递给API路由,该路由将令牌放在它的响应头中。
问题是我的中间件接收到了这个响应(因为API调用是在中间件内部进行的),并且没有设置cookie。我想到了一个主意,即从这个响应中提取头,然后在将用户重定向到他们的目标URL

之前设置这些头
然而,这种方法并没有覆盖我先前存在的旧cookie,我不知道为什么
API:

res.statusCode = 200
res.setHeader("Set-Cookie", [
               cookie.serialize("accessToken", accessToken, {
                    httpOnly: true,
                    // Only send cookie over https when not in dev mode
                    secure: process.env.NODE_ENV !== "development",
                    // 1 hour
                    maxAge: 60 * 60,
                    // Only attached to same site requests
                    sameSite: "strict",
                    // Available everywhere within the site
                    path: "/"
                }),
                cookie.serialize("refreshToken", refreshToken, {
                    httpOnly: true,
                    // Only send cookie over https when not in dev mode
                    secure: process.env.NODE_ENV !== "development",
                    // Only attached to same site requests
                    sameSite: "strict",
                    // Available everywhere within the site
                    path: "/"
                })])
res.send("access and refresh tokens set")

中间件:

const MoveToTargetURL = NextResponse.next();
const tokens = response.headers.get('set-cookie').split(", ")

// Index 0 : Access token
// Index 1 : Refresh token
MoveToTargetURL.headers.set('set-cookie', tokens[0])
MoveToTargetURL.headers.append('set-cookie', tokens[1])

return MoveToTargetURL

我的回复中的标题:

我提取和设置的标头:

2vuwiymt

2vuwiymt1#

我尝试了头文件,也遇到了同样的问题。所以,我这样做了,而不是用cookie序列化。serialize in API发送accessToken和refreshToken作为来自后端和Next js中间件的响应,您可以这样序列化和设置cookie:
API:

res.json({ accessToken, refreshToken });

中间件:

const response = NextResponse.next();

const data = await (
 await fetch(`${process.env.BACKEND_URL}/api/token`, {
  method: "POST",
  body: JSON.stringify({}),
 })
).json();
console.log(data)

response.cookies.set("accessToken", accessToken, {
 httpOnly: true,
 secure: process.env.NODE_ENV !== "development",
 sameSite: "strict",
 maxAge: 60 * 60,
 path: "/",
});
response.cookies.set("refreshToken", refreshToken, {
 httpOnly: true,
 secure: process.env.NODE_ENV !== "development",
 sameSite: "strict",
 path: "/",
});

return response;

希望这对某些人有帮助

相关问题