我正在使用 Next.js 和 Nest.js 制作一个小型应用程序。我正在客户端中进行 /login 调用,服务器应该返回 HttpOnly Cookie。然后,如果响应正常,我们将重定向到主页,这需要对用户进行身份验证。我认为我已经正确完成了此操作,但我不确定我是否遗漏了某些内容,因为我可以在网络请求的响应标头中看到 cookie。我假设 cookie 将出现在我的中间件的请求标头中,但如果不手动设置 cookie,这些都不起作用。 我认为我做错了的另一个原因是因为登录后在浏览器的控制台中,如果我写 document.cookie;我可以看到饼干。
服务器:
@Public()
@HttpCode(HttpStatus.OK)
@Post('signIn')
async signIn(@Body() signInDto: SignInDto, @Res() response: Response) {
const { access_token, role } = await this.authService.signIn(
signInDto.username,
signInDto.password,
);
response.cookie('jwt', access_token, {
sameSite: 'lax',
path: '/',
secure: false,
httpOnly: true,
});
response.send({ message: 'Authenciation Successful', role });
}
客户:
const LoginPage = () => {
// should we move this out to an api folder?
async function handleSubmit(e: FormData) {
"use server";
// const formData = new FormData(e.get);
const username = e.get("username");
const password = e.get("password");
const response = await fetch("http://localhost:8080/auth/signIn", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, password }),
});
console.log("response in cookie ", response.headers.get("Set-Cookie"));
// without this I cannot see the cookie in the browser nor can I make the call on my homepage
const setCookieHeader = response.headers.get("Set-Cookie");
if (setCookieHeader) {
const jwtToken = setCookieHeader.split(";")[0].split("=")[1];
console.log("JWT Token:", jwtToken);
cookies().set({ name: "jwt", value: jwtToken, secure: true, path: "/" });
}
// if (!response.ok) doesn't work investigate
if (!response.ok) {
console.log("Invalid username or password");
// how can we display an error here without state?
return;
}
// redirect to homepage on success
redirect("/");
}
在nestjs中使用。 response.setHeader('Set-Cookie', accessToken);