XMLHttpRequest的withCredentials属性
最近对接第三方网站出现一下错误:
Access to XMLHttpRequest at 'https://third.site.com/request_url' from origin 'https://main.site.com' has been blocked by CORS policy: 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.
根据错误线索查资料:
1.什么是 credentials
credentials,即用户凭证,是指 cookie、HTTP身份验证和TLS客户端证书。
XMLHttpRequest 的 withCredentials 属性:
默认值为false。在获取同域资源时设置 withCredentials 没有影响。
true:在跨域请求时,会携带用户凭证
false:在跨域请求时,不会携带用户凭证;返回的 response 里也会忽略 cookie
2.模拟:
$.ajax({
type: "POST",
url: 'https://third.site.com/request_url',
data: {'userid': '1112233', 'data': 'hello third'},
success: function(data){console.log(data)},
dataType: 'json',
xhrFields: {
withCredentials: true
}
});
Response headers:
Access-Control-Allow-Headers: origin, token
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 3600
Content-Type: application/json;charset=UTF-8
Date: Fri, 08 Mar 2019 10:11:21 GMT
Transfer-Encoding: chunked
查看console,提示文章开头的报错。
3.解决方法:
服务端返回的respoonse上加上:
response.setHeader("Access-Control-Allow-Origin", "https://main.site.com");
response.setHeader("Access-Control-Allow-Credentials", "true");
修改后,返回的请求头如下,浏览器不在报错:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: origin, token
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin: https://main.site.com
Access-Control-Max-Age: 3600
Content-Type: application/json;charset=UTF-8
Date: Sat, 09 Mar 2019 06:22:19 GMT
Transfer-Encoding: chunked
4.想法: 从这个过程发现,如果可以将main.site.com站点的页面中注入类似的ajax请求,就可以将main.site.com的cookie发送到你想要的站点,完成用户凭证盗取,也就是CORS攻击。