The following three conditions must be met for the cross-domain request to carry cookies:
- Cross domain: CORS
- Permission: same-site of set-cookie
- Declaration: withCredentails: true
Cross domain
Cors can solve cross-domain problems. Key points:
- Options Sending conditions and processing of precheck requests
- Response Header Settings
Cookie permissions:
(When it comes to cookies, carrying depends mainly on cross-station)
Cookie same-site configuration in set-cookie:
-
Strict, cookies are not sent on all cross-site requests
-
Lax(default), most cross-site requests do not send cookies.
Request type | The sample | normal | Lax |
---|---|---|---|
link | <a href="..." ></a> |
Send a Cookie | Send a Cookie |
preload | <link rel="prerender" href="..." /> |
Send a Cookie | Send a Cookie |
GET the form | <form method="GET" action="..." > |
Send a Cookie | Send a Cookie |
POST form | <form method="POST" action="..." > |
Send a Cookie | Don’t send |
iframe | <iframe src="..." ></iframe> |
Send a Cookie | Don’t send |
AJAX | $.get("..." ) |
Send a Cookie | Don’t send |
Image | <img src="..." > |
Send a Cookie | Don’t send |
(from www.ruanyifeng.com/blog/2019/0)…
None
To allow cross-site sending. (Secure must also be set.) That is, cookies must be sent across sites only under HTTPS
Relevant details
Preview the request
Judgment conditions:
-
The request method is one of three:
- HEAD
- GET
- POST
-
HTTP headers do not exceed the following fields:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-type: is limited to three values
application/x-www-form-urlencoded
,multipart/form-data
,text/plain
Precheck the request’s Response header:
- Access-Control-Allow-Origin
- Access-Control-Allow-Methods
- Access-Control-Allow-Headers
- Access-Control-Allow-Credentials
- Access-Control-Max-Age
Normal cross-domain request
request header
The browser automatically adds the Origin field
response header
-
Access-control-allow-origin: Indicates the allowed domain
-
Access-control-allow-credentials: Specifies whether cookies are allowed
- Access-control-allow-origin cannot be set to * if it is true
-
Access-control-expose-headers: Which Headers in a response are allowed to the client
The thinking behind it:
Cross-domain mainly brings some security problems. If users log in to a website and visit other websites, they can carry cookies of logged websites to perform some dangerous operations.
- Get user information,
- Dangerous operation
- Obtain browsing traces of users (put pictures of station B in Station A, and station B can know which web page A user browsees according to cookie request)
Defense measures:
-
HttpOnly: disallows script to read cookies
- Prevents XSS from stealing cookies
-
Secure: Must be sent over HTTPS
-
SameSite: Disables sending cookies across sites
So it’s best not to cross domains
- Production environments should use proxies to avoid cross-domains