同源策略: 同源策略是浏览器保护用户安全上网的重要措施,协议、域名、端口号三者相同即为同源。
同站 :只要两个 URL 的 eTLD+1 相同即可 否则就是跨站 www.a.com 和 www.b.com
跨域 :不符合同源策略的就属于跨域,如: second.a.com 和 www.a.com
注: 跨站一定跨域,跨域不一定跨站
eTLD : effective top-level domain(有效顶级域)
PSL : 公共后缀列表
「链接」
Internet 用户可以(或在历史上可以)直接在公共后缀(public suffix)上注册名称。如 .com, .ci.uk, pvt.k12.ma.us。(我理解和 eTLD 是一回事)
以nginx为例:
一般这样就能解决跨域了,但是要解决跨域cookie传递,进一步修改为
配合前端传递withCredentials即可
下载地址: https://github.com/FiloSottile/mkcert/releases/latest
进入安装目录,运行
生成证书
同源时cookie的存储与发送没有问题,顶级导航的情况可以看作是同源场景;
不同源场景,若 withCredentials=false,则浏览器不会存储cookie;
不同源场景,且withCredentials=true,又可分为以下场景:
附SameSite各值Cookie发送情况:
后端API同时设置Access-Control-Allow-Credentials的值为true,Access-Control-Allow-Origin的值为*会报The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported.错误。
若前端XHR请求中设置withCredentials为true,但后台API未设置Access-Control-Allow-Credentials,则会报The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.错误。
若前端XHR请求中设置withCredentials为true,但后台API配置Access-Control-Allow-Origin的值为*,则会报The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.错误。
评论留言