Recently, when I started a local project, I found that the request header could not carry cookies when sending a cross-domain request. After surfing the Internet, I found that many people would encounter this problem when developing, so I made a record here
why
When Chrome is upgraded to version 80, the default value of the SameSite property of the cookie changes from None to Lax.
In Lax mode, the following cross-domain methods are affected:
So when we send the cross-domain request, we have not been able to carry the cookie, it is you! Same – site property!!!!!!
What the hell is SameSite
Now that we know why, let’s take a look at what SameSite is and why Google is changing it around
Websites use cookies to record users’ login status, but a disadvantage of cookies is that they can be carried by third party request headers, which is also the cause of CSRF attack. In order to solve this problem at the source, Google started from Chrome 51. A new SameSite property is added to the browser Cookie to protect against CSRF attacks and user tracking.
The three values of SameSite
Respectively is:
- Strict
- Lax
- None
Strict
Strict is the strictest and completely forbids third-party cookies. Cookies are never sent across sites under any circumstances. In other words, cookies are carried only if the URL of the current web page matches the target of the request.
Set-Cookie: CookieName=CookieValue; SameSite=Lax;
Copy the code
This rule is too strict and can lead to a very bad user experience. For example, if there is a GitHub link on the current webpage, users will not have GitHub cookies when they click the jump, and the jump will always be unlogged.
Lax
The Lax rule is slightly relaxed, and third-party cookies are also not sent in most cases, except for Get requests that navigate to the target url.
Set-Cookie: CookieName=CookieValue; SameSite=Lax;
Copy the code
Setting Strict or Lax basically eliminates CSRF attacks. Assuming, of course, that the user’s browser supports the SameSite property.
None
Chrome plans to make Lax the default. At this point, the site can choose to explicitly turn off the SameSite property and set it to None. However, the Secure attribute must be set at the same time (cookies can only be sent through HTTPS). Otherwise, cookies are invalid. The following Settings are invalid.
Set-Cookie: widget_session=abc123; SameSite=None
Copy the code
The following Settings are valid
Set-Cookie: widget_session=abc123; SameSite=None; Secure
Copy the code
The solution
Setting the SameSite property to None solves the problem of carrying cookies across domains. There are three ways to solve the problem:
- Setting the browser
For chrome://flags/ Set SameSite by default cookies to disabled
- Backend response header Settings:
Set-Cookie: widget_session=abc123; SameSite=None; Secure
- Nginx Settings:
Nginx location: proxy_cookie_path/”/; httponly; secure; SameSite=None”;