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

  • 相关阅读:
    Django 之 admin管理工具
    第二十七天- 网络通信协议 TCP UDP 缓冲区
    第二十六天- C/S架构 通信流程 socket
    第二十五天- 包
    第二十四天- 模块导入 import from xxx import xxx
    第二十三天- 模块 re
    第二十二天- 序列化 pickle json shelve
    第二十一天- 基本模块
    第二十天- 多继承 经典MRO 新式MRO super()
    第十九天- 约束 异常处理 日志使用
  • 原文地址:https://www.cnblogs.com/niulang85/p/10501058.html
Copyright © 2011-2022 走看看