Cookies标头存在,但Cookie未存储在浏览器中 [英] Cookies headers are present but Cookies are not stored in browser
问题描述
请帮助我弄清楚为什么在响应标头中存在Set-Cookie标头的情况下,浏览器(Chrome和其他任何浏览器)为何未设置Cookie的原因:
Please help me to figure out why the browser (Chrome and any others) does not set cookies, while Set-Cookie header is present in Response Headers:
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 345
Content-Type: application/json; charset=utf-8
Date: Sat, 18 Jan 2020 21:15:53 GMT
ETag: W/"159-UXuykOchcveuYBb7xZpN5Luf3jU"
Set-Cookie: jwt=************; Path=/; Expires=Fri, 17 Apr 2020 21:15:53 GMT; HttpOnly
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
我的应用运行在: http:// localhost:8080
推荐答案
您似乎正在使用CORS。
You seem to be using CORS.
要使用CORS设置Cookie,您在发出请求时需要设置 withCredentials
标志。
To set a cookie with CORS you'll need to set the withCredentials
flag when making the request.
https ://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials
服务器将需要返回标头 Access-Control-Allow-Credentials:true
。您还需要更改 Access-Control-Allow-Origin:*
,因为您不能在使用凭据的请求上使用通配符。
The server will need to return the header Access-Control-Allow-Credentials: true
. You'll also need to change the Access-Control-Allow-Origin: *
as you can't use wildcards on a request that uses credentials.
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
https://developer.mozilla.org/zh-CN/docs/Web / HTTP / Headers / Access-Control-Allow-Origin
从Chrome 80开始,您还需要设置 SameSite =在Cookie上没有$
和 Secure
指令。
As of Chrome 80 you'll also need to set SameSite=None
and Secure
directives on the cookie.
https://www.chromestatus.com/feature/5088147346030592
h ttps://www.chromestatus.com/feature/5633521622188032
> https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/
要检查是否设置了cookie,您不能简单地打开 Application> Cookies 来检查cookie。 Cookie将设置为 localhost:3000
,因此查看 localhost:8080
的cookie将不会显示它。相反,您需要打开另一个指向 localhost:3000
的标签,然后在其中查看 Application> Cookies 。 Cookie在标签之间共享,因此您仍然可以看到由原始 localhost:8080
标签设置的Cookie。
To check whether a cookie is set you cannot simply open Application > Cookies to check for the cookie. The cookie will be set for localhost:3000
so looking at the cookies for localhost:8080
won't show it. Instead you'll need to open another tab that points to localhost:3000
and then look at Application > Cookies in there. Cookies are shared between tabs so you'll still be able to see the cookies set by the original localhost:8080
tab.
让跨域Cookie与Safari配合使用是另一回事。如果您需要支持Safari,建议您做一些研究,因为您可能需要完全采用其他策略。
Getting cross-origin cookies to work with Safari is a separate struggle. If you need to support Safari I suggest you do some research into that as you may need to adopt a different strategy altogether.
这篇关于Cookies标头存在,但Cookie未存储在浏览器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!