关于跨域:项目中遇到的跨域问题解决

4次阅读

共计 1455 个字符,预计需要花费 4 分钟才能阅读完成。

带 credentials 的 CORS 申请

Credentials 与 CORS

Credentials(凭证) 能够是 cookies, authorization headers 或 TLS client certificates。
CORS 申请默认不发送 Credentials。

如何让 CORS 申请发送 Credentials?

如果要让带 credentials 的 CORS 申请胜利,前后端都须要配置。否则,即便服务器批准发送 Cookie,浏览器也不会发送。或者,服务器要求设置 Cookie,浏览器也不会解决。

Cookie 仍然遵循同源政策,只有用服务器域名设置的 Cookie 才会上传,其余域名的 Cookie 并不会上传

配置

后端配置:
Access-Control-Allow-Credentials header;
前端配置:
XHR 配置 withCredentials 或 Fetch request 配置 credentials;

Access-Control-Allow-Credentials

它的值是一个布尔值,示意是否容许发送 Cookie。默认状况下,Cookie 不包含在 CORS 申请之中。设为 true,即示意服务器明确许可,Cookie 能够蕴含在申请中,一起发给服务器。
如果服务器不要浏览器发送 Cookie,删除该字段即可。

Request.credentials

credentialsRequest 接口的只读属性,用于示意用户代理是否应该在跨域申请的状况下从其余域发送 cookies。有三个可选值:

  • omit: 从不发送 cookies。
  • same-origin: 只有当 URL 与响应脚本同源才发送 cookies、HTTP Basic authentication 等验证信息。
  • include: 不论是不是跨域的申请, 总是发送申请资源域在本地的 cookies、HTTP Basic authentication 等验证信息。

XMLHttpRequest.withCredentials

withCredentials是一个 Boolean 类型,如果是 true, 执行跨域申请时会带上 Credentials,否则不会携带。默认值是 false。

  • 如果在发送来自其余域的 XMLHttpRequest 申请之前,未设置withCredentials 为 true,那么就不能为它本人的域设置 cookie 值。
  • 通过设置withCredentials 为 true 取得的第三方 cookies,将会仍旧享受同源策略,不能被通过 document.cookie 或者从头部相应申请的脚本等拜访。
  • 在同一个站点下应用 withCredentials 属性是有效的。它永远不会影响到同源申请。

例子

后端容许 credentials:

Access-Control-Allow-Credentials: true

前端应用带 credentials 的 XHR 申请:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

前端应用带 credentials 的 Fetch 申请:

fetch(url, {credentials: 'include'})

当 credentials 是 include 时,Access-Control-Allow-Credentials 必须设置为 true; 当 credentials 是其余值时,能够不设置 Access-Control-Allow-Credentials。

正文完
 0