简体   繁体   English

React/Express set-cookie 不能跨不同的子域工作

[英]React/Express set-cookie not working across different subdomains

I have a React frontend with Express API server, and I am trying to store a JWT in a secure httpOnly cookie for authorization.我有一个带有 Express API 服务器的 React 前端,我正在尝试将 JWT 存储在安全的 httpOnly cookie 中以进行授权。 Below are the relevant parts of my code, which includes everything I've tried from countless Google/StackOverflow searches.以下是我的代码的相关部分,其中包括我从无数 Google/StackOverflow 搜索中尝试过的所有内容。

Am I missing something simple?我错过了一些简单的东西吗? I am trying to avoid storing the JWT in localStorage , but I am just at a loss right now.我试图避免将 JWT 存储在localStorage中,但我现在不知所措。 Nothing seems to work.似乎没有任何效果。

API ( https://api.mydomain.com ): APIhttps://api.mydomain.com ):

app.use(cors({
  credentials: true,
  exposedHeaders: ['SET-COOKIE'],
  origin: 'https://staging.mydomain.com',
}));

app.post('/auth/login', (request, response) => {
  ...

  response.cookie('jwt', JWT.sign({ id: user.id }, ...), {
    domain: 'mydomain.com',
    httpOnly: true,
    sameSite: 'none',
    secure: true,
  });

  response.json(user);
});

Web ( https://staging.mydomain.com ): Webhttps://staging.mydomain.com ):

await fetch('https://api.mydomain.com/auth/login', {
  body: JSON.stringify({ ... }),
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json',
  },
  method: 'POST',
});

I see the set-cookie header in the response, but I do not see the cookie set in the developer tools and it is not passed in subsequent API requests.我在响应中看到了set-cookie header,但是我没有看到开发者工具中设置的 cookie,并且在后续的 API 请求中也没有传递。

Response Headers:
access-control-allow-credentials: true
access-control-allow-origin: https://staging.mydomain.com
access-control-expose-headers: SET-COOKIE
set-cookie: jwt=abcde*********.abcde*********.abcde*********; Domain=mydomain.com; Path=/; HttpOnly; Secure; SameSite=None

On your server, when you are setting the cookie, can you try adding a dot before the domain.在您的服务器上,当您设置 cookie 时,您可以尝试在域之前添加一个点。 The leading dot implies that the cookie is valid for subdomains as well.前导点表示 cookie 对子域也有效。

response.cookie('jwt', JWT.sign({ id: user.id }, ...), {
  domain: '.mydomain.com',
  httpOnly: true,
  sameSite: 'none',
  secure: true,
});

When the client (here, https://staging.mydomain.com ) will receive the Set-Cookie response header, with the trailing dot domain, it would accept the cookie since now the cookie is valid for subdomains too.当客户端(此处为https://staging.mydomain.com )将收到Set-Cookie响应 header 时,它现在将接受有效的子 cookie,因为它现在也将接受域的 cookie。

On a side note, I find Cookie Editor really helpful for debugging cookies.另一方面,我发现Cookie 编辑器对调试 cookies 非常有帮助。

Hope this answer helps you: :)希望这个答案对您有所帮助::)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM