【问题标题】:Cookies not being sent despite credentials: "include"尽管有凭据但未发送 Cookie:“包括”
【发布时间】:2021-10-13 22:45:16
【问题描述】:

我在后端使用 express,在前端使用 react。我正在使用 cors 从 passport.js GoogleOAuth 中获取用户详细信息。我正在使用 Heroku 在两个不同的域中托管前端和后端。客户端中的请求如下所示:

fetchAuthUser = async () => {
    const metadata = {
      headers : {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      referrerPolicy: "strict-origin-when-cross-origin",
      body: null,
      method: "GET",
      mode: "cors",
      credentials: "include"
    }
    
    const response = await fetch(Env.backend_host +'/authenticate_google/api/current_user', metadata).catch((err) => {
        console.log(err)
    });

    console.log(response);

    if (response && response.data) {
      this.setState({user: eval(response.data)}, () => {this.loadPages()});
    }
  }

并且服务器当前设置如下:

cookies是这样设置的,

router.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000, // sets cookie to expire in 30 days (converted to milliseconds)
    keys: ["trialkey"],
    sameSite: "lax",
  })
);

get 响应如下

router.get("/api/current_user", cors({ origin: "https://energycast-front.herokuapp.com", methods: ['GET','POST','OPTIONS'], credentials: true, preflightContinue: true}), (req, res) => {

    console.log("User:" +req.user)

    res.json(req.user);
 
  });

问题似乎与 cors 无关,但是在观察请求时,我看到没有发送任何 cookie。这很奇怪,因为我设置了凭据“包含”。

注意,控制台正在记录服务器本身未定义的“用户”。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs express cookies cross-domain


    【解决方案1】:

    如果请求来自不同的站点并且不是由顶级导航(而是由fetch 语句)发起的,则带有SameSite=Lax 的Cookie 将被阻止。

    尝试使用sameSite: "None"

    该 cookie 也可能被阻止,因为它违反了您浏览器中的第三方 cookie 设置。

    【讨论】:

    • 我尝试使用带有附加安全标签的 sameSite: "None" 但仍然没有成功。
    • @JuanCarlosBoschero,浏览器开发工具会告诉你 cookie 被阻止的原因吗?例如,Chrome DevTools > Network > Cookies 包含非常详细的信息。
    • 非常感谢您的洞察力,我查看了前端的网络标签,cookie 以黄色突出显示,说明“cookie 未指定 SameSite,因此设置为 Lax默认”。但是我目前有这样的代码集:router.use( cookieSession({ maxAge: 30 * 24 * 60 * 60 * 1000, keys: ["trialkey"], sameSite: "none", secure: true }) );
    • 也许cookie-session 不支持sameSitenpmjs.com/package/cookie-session#cookie-options上没有提到
    • 我试过调查它,但它似乎应该可以工作,因为您展示的网站是两年前发布的,并且一年前用sameSite标签stackoverflow.com/questions/63680921/…提出了类似的问题。我还通过重写代码将httpOnly:true 设置为true 来查看线程中是否存在问题,但仍然没有。
    【解决方案2】:

    我已经弄清楚出了什么问题,问题出在 cookie-session 中。当 cookie 设置为 sameSite = 'none' 时,网络工具会拾取它并返回安全必须设置为 true 的错误。但是,在将 secure 设置为 true 后,网络调试工具恢复为相同站点设置为“Lax”并且无法发送 cookie。

    我因此切换到 express-cookie 包:

    router.set('trust proxy', 1) // trust first proxy
    router.use(
      session({
        secret: SECRET,
        resave: false,
        saveUninitialized: true,
        cookie: { 
          secure: true,
          sameSite: "none"
        }
      })
    );
    

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 1970-01-01
      • 2014-06-22
      • 2017-07-01
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      相关资源
      最近更新 更多