如果没有 SameSite 属性给我未定义或域也无效,我如何在我的网站上接收 Cookie

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

当我使用 axios 向服务器发出请求并在 true 中添加凭据时

const sendCredentials = async (formData) =\> {
try {
const response = await httpService.post("/login", formData, {
withCredentials: true,
});
return response.data;

} catch (error) {
if (error) {
return error;
}
}
};

我的服务器,配置如下:

const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const cookieParser = require("cookie-parser");

const sequelize = require("./database/database");

require("./models/User");

const authRoutes = require("./routes/auth.routes");

createRoles();

const app = express();
app.use(cookieParser());

app.use(
  cors({
    origin: [config.origin.client], 
    credentials: true, 
  })
);

app.use(morgan("dev")); 
app.use(express.json()); 

app.use(authRoutes);

const PORT = process.env.PORT || 4000;

async function main() {
  try {
    await sequelize.sync({ alter: true, logging: false });

    app.listen(PORT, () => {
      console.log(`Servidor backend escuchando en el puerto ${PORT}`);
    });
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  }
}

main();

接收请求并通过“/login”路由执行以下操作:

const login = async (req, res) => {
  const { email, password } = req.body;

  const user = await User.findOne({
    where: {
      email,
    },
    include: [Role],
  });

  if (!user) {
    return res.status(401).json({ error: "User not found" });
  } 
  const storedHashedPassword = user.password;

  const isPasswordMatch = await compare(password, storedHashedPassword);

  if (!isPasswordMatch) {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  const token = sign(
    {
      exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30,
      id: user.id,
      email: user.email,
      username: user.name,
    },
    config.secretSignJwt
  );

  const serialized = serialize("myTokenName", token, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: 1000 * 60 * 60 * 24 * 30,
    domain: "kids-ecommerce.vercel.app",
    path: "/",
  });

  res.cookie(serialized);
  res.json("succesfull");
};

然后在浏览器中我正确地接收到状态为 200 的响应,我可以在其中获取 cookie 和其他数据,但是 SameSite 属性附带值 Lax=undefined 并且该域显示为不允许,因此我无法将其设置为 cookie。

这里我为您提供浏览器中注册的服务器响应的更多详细信息:

Request URL:  https://e-commerce-backend-self.vercel.app/login
Request Method: POST
Status Code: 200
Remote Address: 76.76.21.93:443
Referrer Policy: strict-origin-when-cross-origin

Response Headers:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, DELETE
Access-Control-Allow-Origin: https://kids-ecommerce.vercel.app
Cache-Control: public, max-age=0, must-revalidate
Content-Length: 12
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Jul 2023 16:18:01 GMT
Etag: W/"c-pW/4RryX/+LCeLkf5W6sZxG5ayI"
Server: Vercel
Set-Cookie: myTokenName=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTMxNTMwODEsImlkIjoiNmZhMWRlN2YtYWRkYy00MzRiLWIzYmQtZTMxYWE5YTViM2Y3IiwiZW1haWwiOiJyaXNiZWw5NjEwMTlAZ21haWwuY29tIiwidXNlcm5hbWUiOiJSaXNiZWwiLCJpYXQiOjE2OTA1NjEwODF9.bEz37GHzE4UoXRONn_P_FgkjhlZ93NjCta0Tsd0C_RQ; Max-Age=2592000000; Domain=kids-ecommerce.vercel.app; Path=/; Secure; SameSite=Lax=undefined; Path=/

我想要的只是浏览器停止警告我:

( 某些 cookie 滥用推荐属性“SameSite” 值“SameSite”对于 cookie“myTokenName”无效。支持的值为:“Lax”、“Strict”、“None”。 cookie“myTokenName”没有正确的“SameSite”属性值。很快,没有“SameSite”属性或具有无效值的 cookie 将被视为“Lax”。这意味着 cookie 不再在第三方上下文中发送。如果您的应用程序依赖于此 cookie 在此类上下文中可用,请添加属性“SameSite=none”。要了解有关“SameSite”属性的更多信息,请阅读 https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite

cookie“myTokenName”已被无效域拒绝。 )

并正确设置cookie。

如果您能帮助我解决这个问题,我将非常感谢社区...

node.js express cookies next.js setcookie
© www.soinside.com 2019 - 2024. All rights reserved.