zoukankan      html  css  js  c++  java
  • 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攻击。

  • 相关阅读:
    MyEclipse2014中SVN的使用方法
    使用Navicat V8.0创建数据库,外键出现错误ERROR 1005: Can’t create table (errno: 121)
    个人简历
    Android Studio集成SVN报错:can't use subversion command line client : svn
    面向对象原型的七种方法详解(前)
    js中return的用法
    面试题总结
    Ajax 是什么?Ajax 的交互模型?同步和异步的区别?如何解决跨域问题?以及 HTTP状态码
    css3实现的3中loading动画效果
    CSS3绘制弹球动画效果
  • 原文地址:https://www.cnblogs.com/niulang85/p/10501058.html
Copyright © 2011-2022 走看看