Cookies headers are present but Cookies are not stored in browser

人走茶凉 提交于 2020-08-09 07:00:38

问题


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

My app running at: http://localhost:8080


回答1:


You seem to be using CORS.

To set a cookie with CORS you'll need to set the withCredentials flag when making the request.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

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/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

As of Chrome 80 you'll also need to set SameSite=None and Secure directives on the cookie.

https://www.chromestatus.com/feature/5088147346030592
https://www.chromestatus.com/feature/5633521622188032
https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/

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.

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.



来源:https://stackoverflow.com/questions/59808537/cookies-headers-are-present-but-cookies-are-not-stored-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!