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攻击。

 

转载于:https://www.cnblogs.com/niulang85/p/10501058.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值