【问题标题】:what is the correct way of setting httpOnly cookie in the browser with CORS?使用 CORS 在浏览器中设置 httpOnly cookie 的正确方法是什么?
【发布时间】:2021-06-06 08:17:49
【问题描述】:

我有一个节点 js 服务器在 https://foo.test.com 上运行,其中身份验证 API 返回一个 httpOnly cookie,当站点位于 https://bar.test.com 时,该 cookie 未在浏览器中设置。

从服务器端设置 cookie:

ctx.cookies.set('foo', 'bar', {
  httpOnly: true,
  maxAge: 8.64e+7,
  sameSite: 'strict',
  secure: true,
  domain: 'test.com',
});

CORS 配置

app.use(cors({
    origin: 'https://bar.test.com',
    credentials: true,
})).use(bodyParser()).use(jwt).use(router.routes());

客户端身份验证api

fetch('/validate-otp', {
  method: 'PUT',
  headers: {
     Accept: 'application/json',
     'Content-Type': 'application/json',
   }, 
  credentials: 'include',   
})

我已经在服务器上设置了一个测试API,看看cookie是否设置为如下所示的标头,即使它暂时不起作用。

fetch('/test', {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    'content-Type': 'application/json',
  },
  credentials: 'include',
});

在浏览器中,我可以看到我收到了带有响应的 cookie,但它没有被设置。

如何在浏览器中正确设置 httpOnly cookie,以便将其作为标头发送给未来的服务器请求?

【问题讨论】:

  • 这可能是客户端问题。您是否在xhr 对象上设置了withCredentials = true?请分享浏览器的代码。
  • 我已编辑问题以包含客户端代码。

标签: javascript reactjs cookies fetch cross-domain


【解决方案1】:

设置后,cookie 会自动附加到所有请求。我将从更改maxAge 开始。由于测量单位是毫秒,因此您的 cookie 将无法发送(60*60ms = 3600ms = 3.6s),也许像 maxAge: 8.64e+7 这样的东西 - 对应于 24 小时 - 可以工作。

httpOnly 属性可防止任何客户端 javascript 访问它,但对于您的身份验证而言,这是一种合理的行为。

【讨论】:

  • 我试过了,我不认为 maxAge 是这里的问题。
【解决方案2】:

在深入挖掘之后,我通过将用于从服务器获取 cookie 的身份验证 API 的 fetch 方法从“PUT”更改为“POST”解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2021-07-05
    • 2021-02-28
    • 2012-12-22
    • 2010-10-13
    相关资源
    最近更新 更多