Cross-domain problems and solutions cross-domain problems and solutions

Cross-domain problems and solutions

 

 


1. What is cross-domain

  • The risks of cross-domain?

    • Cross-domain requests and Ajax technology will greatly enhance the experience of the page, but it also brings security risks, the most important risks from CSRF (Cross-Site Request Forgery) cross-site request forgery.

    • General principle csrf attacks

      If a bank transfer operations to run at the following URL:http://www.examplebank.com/withdraw?account=AccoutName&amount=1000&for=PayeeName

      Well, a malicious attacker could place a picture can not be described on another website to lure you click on, click on the picture to send requests to "http://www.examplebank.com/withdraw?account=Alice&amount=1000&for=Badman"

      If you have an account with a user named Alice visited a malicious site, and she had just visited the bank shortly before the login information has not yet expired, then she will lose 1000 funding.

  • Cross-domain means that we visit a website, such as: http: //127.0.0.1: 8000 this url, went to visit this url http://127.0.0.1:9000 from this page, this time triggered a cross-domain, when the domain name, port, two different domain names will lead to cross-domain. At this point the server port 9000 can receive the request, the response data will give the browser, but the browser arrives after being intercepted, because same-origin policy browser.

    URL result the reason
    http://www.cnblogs.com/liuweida success Domain name, protocol, the same port
    https://www.cnblogs.com/liuweida failure Different protocols
    http://www.cnblogs.com:8888/liuweida failure Different port
    http://www.cnblogs.cn/liuweida failure Different domain

2. What is the origin policy?

  • Origin policy is a convention, it is also the core browser is the most basic security feature, if the lack of the same origin policy, the normal function of the browser may be affected. It agreed to request the url address, url must be in the browser's address on the same domain, which is the domain name, port, protocol are the same. If not, the error will be:

  • In fact, the result is that the request has been sent over, the target server also responded to the request, but the browser returns a result of non-homologous request made to intercept.

Unlimited number of embedded resources

Such as:

  • <script src="..."></script> Tags embedded in cross-domain scripting. Syntax error information can only be captured in homologous script.
  • <link rel="stylesheet" href="..."> Tags embedded CSS.
  • <img> Embedded picture.
  • <video> And  <audio> embedded multimedia resources.
  • <object><embed> And  <applet>plug-ins.
  • @font-face The introduction of the font. Some browsers allow cross-domain fonts (cross-origin fonts), fonts that require homologous (same-origin fonts).
  • <frame> And  <iframe>loading of any resource. Sites can use the X-Frame-Options news head to prevent this form of cross-domain interaction.

Limits

Non-homologous sites, there are three kinds of behavior are limited

  1. Can not share cookie, localStorage, indexDB
  2. We can not operate with each other DOM element
  3. Unable to send Ajax request

3. How to solve the problem of cross-domain request to send

3.1 jsonp

  • jsonp stands for JSON with Padding, solutions to solve cross-domain requests resources generated, rely on a developer to create an unofficial cross-domain data exchange protocol.

  • Based on cross-domain script tag implementation

    <!DOCTYPE html>
    <html>
    <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var messagetow = function(data){ alert(data); }; var url = "http://192.168.31.137/train/test/jsonpthree?callback=messagetow"; var script = document.createElement('script'); script.setAttribute('src', url); document.getElementsByTagName('body')[0].appendChild(script); </script> </head> <body> </body> </html>
  • Based on cross-domain jquery

    $.ajax({
         type : 'get',
         url:'http://192.168.31.137/train/test/testjsonp',
         data : { name : name, sex : sex, address : address, looks : looks, }, cache :false, jsonp: "callback", jsonpCallback:"success", dataType : 'jsonp', success:function(data){ alert(data); }, error:function(data){ alert('error'); } });

3.2 cors [recommended]

  • CORS ( Cross-Origin Resource Sharing , cross-domain resource sharing) is a W3C standard that defines when the resource must be accessed across domains, browsers and servers should be how to communicate (requires the client and server co-processing) .
  • CORS two requests, simple and non-simple request requests.

Simple request

  • What is a simple request?

    只要同时满足以下两大条件,就属于简单请求。
    1)请求方法是以下三种方法之一:
      - HEAD
      - GET
      - POST
    (2)HTTP的头信息不超出以下几种字段:
      - Accept
      - Accept-Language
      - Content-Language
      - Last-Event-ID
      - Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain
  • Achieve a simple request cors

    1.前端不需要进行特殊的操作
    2.后端需要加入请求头Access-Control-Allow-Origin,代码如下:
        def get_time(request): if request.method == 'GET': ntime = time.strftime('%Y-%m-%d %X') obj = HttpResponse(ntime) obj['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001' return obj

Complex requests

  • Two requests, before starting the transmission data is first requested to do pre-screening, and only after pre-screening by sending a request as a data transmission.

    - 请求方式:OPTIONS
    - “预检”其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
    - 如何“预检”
      => Access-Control-Allow-Origin(必含)
         设置为'*',允许所有域名访问
         一般设置为指定域名,如:'Access-Control-Allow-Origin:http://192.168.12.87'
      => 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则“预检”不通过
            Access-Control-Request-Method
      => 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则“预检”不通过
            Access-Control-Request-Headers
  • Complex requests realization

    front end

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    <button id="a" class="btn btn-success">go</button>
    <script>
        $("#a").click(function () {
            $.ajax({
                url:'http://127.0.0.1:8000/money/',
                type:'post',
                contentType:'application/json',
                data:{"name":"yjh"},
                success:function (data) {
                    alert(data)
                }
                }
            )
        })
    </script>
    </body>
    </html>

    Backstage

    from django.http import QueryDict
    def get_money(request,response): if request.method == 'OPTIONS': response['Access-Control-Allow-Origin'] = '*' # 允许所有域名访问,一般会设置成指定的域名 response['Access-Control-Allow-Headers'] = 'Content-Type' # 复杂请求添加的头信息 response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001' return response

Global Configuration

  • Global Configuration can be written in the middleware, the browser is the received return data occur when disabled, so you can add response headers in the data return, so the rewrite middleware process_response method

  • Step a: In the following code written py file:

    from django.utils.deprecation import MiddlewareMixin
    class CorsMiddleWare(MiddlewareMixin): def process_response(self,request,response): if request.method=="OPTIONS": response['Access-Control-Allow-Origin'] = 'http://localhost' response["Access-Control-Allow-Headers"]="Content-Type" response["Access-Control-Allow-Origin"] = "http://localhost:8080" return response
  • Step two: add middleware registered in the configuration file in settings.py

    MIDDLEWARE = [
        'app01.my_middleware.CorsMiddleware',  # 在第一行写是因为django中间件的执行顺序,process_response倒序执行
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]

 


1. What is cross-domain

  • The risks of cross-domain?

    • Cross-domain requests and Ajax technology will greatly enhance the experience of the page, but it also brings security risks, the most important risks from CSRF (Cross-Site Request Forgery) cross-site request forgery.

    • General principle csrf attacks

      If a bank transfer operations to run at the following URL:http://www.examplebank.com/withdraw?account=AccoutName&amount=1000&for=PayeeName

      Well, a malicious attacker could place a picture can not be described on another website to lure you click on, click on the picture to send requests to "http://www.examplebank.com/withdraw?account=Alice&amount=1000&for=Badman"

      If you have an account with a user named Alice visited a malicious site, and she had just visited the bank shortly before the login information has not yet expired, then she will lose 1000 funding.

  • Cross-domain means that we visit a website, such as: http: //127.0.0.1: 8000 this url, went to visit this url http://127.0.0.1:9000 from this page, this time triggered a cross-domain, when the domain name, port, two different domain names will lead to cross-domain. At this point the server port 9000 can receive the request, the response data will give the browser, but the browser arrives after being intercepted, because same-origin policy browser.

    URL result the reason
    http://www.cnblogs.com/liuweida success Domain name, protocol, the same port
    https://www.cnblogs.com/liuweida failure Different protocols
    http://www.cnblogs.com:8888/liuweida failure Different port
    http://www.cnblogs.cn/liuweida failure Different domain

2. What is the origin policy?

  • Origin policy is a convention, it is also the core browser is the most basic security feature, if the lack of the same origin policy, the normal function of the browser may be affected. It agreed to request the url address, url must be in the browser's address on the same domain, which is the domain name, port, protocol are the same. If not, the error will be:

  • In fact, the result is that the request has been sent over, the target server also responded to the request, but the browser returns a result of non-homologous request made to intercept.

Unlimited number of embedded resources

Such as:

  • <script src="..."></script> Tags embedded in cross-domain scripting. Syntax error information can only be captured in homologous script.
  • <link rel="stylesheet" href="..."> Tags embedded CSS.
  • <img> Embedded picture.
  • <video> And  <audio> embedded multimedia resources.
  • <object><embed> And  <applet>plug-ins.
  • @font-face The introduction of the font. Some browsers allow cross-domain fonts (cross-origin fonts), fonts that require homologous (same-origin fonts).
  • <frame> And  <iframe>loading of any resource. Sites can use the X-Frame-Options news head to prevent this form of cross-domain interaction.

Limits

Non-homologous sites, there are three kinds of behavior are limited

  1. Can not share cookie, localStorage, indexDB
  2. We can not operate with each other DOM element
  3. Unable to send Ajax request

3. How to solve the problem of cross-domain request to send

3.1 jsonp

  • jsonp stands for JSON with Padding, solutions to solve cross-domain requests resources generated, rely on a developer to create an unofficial cross-domain data exchange protocol.

  • Based on cross-domain script tag implementation

    <!DOCTYPE html>
    <html>
    <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var messagetow = function(data){ alert(data); }; var url = "http://192.168.31.137/train/test/jsonpthree?callback=messagetow"; var script = document.createElement('script'); script.setAttribute('src', url); document.getElementsByTagName('body')[0].appendChild(script); </script> </head> <body> </body> </html>
  • Based on cross-domain jquery

    $.ajax({
         type : 'get',
         url:'http://192.168.31.137/train/test/testjsonp',
         data : { name : name, sex : sex, address : address, looks : looks, }, cache :false, jsonp: "callback", jsonpCallback:"success", dataType : 'jsonp', success:function(data){ alert(data); }, error:function(data){ alert('error'); } });

3.2 cors [recommended]

  • CORS ( Cross-Origin Resource Sharing , cross-domain resource sharing) is a W3C standard that defines when the resource must be accessed across domains, browsers and servers should be how to communicate (requires the client and server co-processing) .
  • CORS two requests, simple and non-simple request requests.

Simple request

  • What is a simple request?

    只要同时满足以下两大条件,就属于简单请求。
    1)请求方法是以下三种方法之一:
      - HEAD
      - GET
      - POST
    (2)HTTP的头信息不超出以下几种字段:
      - Accept
      - Accept-Language
      - Content-Language
      - Last-Event-ID
      - Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain
  • Achieve a simple request cors

    1.前端不需要进行特殊的操作
    2.后端需要加入请求头Access-Control-Allow-Origin,代码如下:
        def get_time(request): if request.method == 'GET': ntime = time.strftime('%Y-%m-%d %X') obj = HttpResponse(ntime) obj['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001' return obj

Complex requests

  • Two requests, before starting the transmission data is first requested to do pre-screening, and only after pre-screening by sending a request as a data transmission.

    - 请求方式:OPTIONS
    - “预检”其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
    - 如何“预检”
      => Access-Control-Allow-Origin(必含)
         设置为'*',允许所有域名访问
         一般设置为指定域名,如:'Access-Control-Allow-Origin:http://192.168.12.87'
      => 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则“预检”不通过
            Access-Control-Request-Method
      => 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则“预检”不通过
            Access-Control-Request-Headers
  • Complex requests realization

    front end

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    <button id="a" class="btn btn-success">go</button>
    <script>
        $("#a").click(function () {
            $.ajax({
                url:'http://127.0.0.1:8000/money/',
                type:'post',
                contentType:'application/json',
                data:{"name":"yjh"},
                success:function (data) {
                    alert(data)
                }
                }
            )
        })
    </script>
    </body>
    </html>

    Backstage

    from django.http import QueryDict
    def get_money(request,response): if request.method == 'OPTIONS': response['Access-Control-Allow-Origin'] = '*' # 允许所有域名访问,一般会设置成指定的域名 response['Access-Control-Allow-Headers'] = 'Content-Type' # 复杂请求添加的头信息 response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001' return response

Global Configuration

  • Global Configuration can be written in the middleware, the browser is the received return data occur when disabled, so you can add response headers in the data return, so the rewrite middleware process_response method

  • Step a: In the following code written py file:

    from django.utils.deprecation import MiddlewareMixin
    class CorsMiddleWare(MiddlewareMixin): def process_response(self,request,response): if request.method=="OPTIONS": response['Access-Control-Allow-Origin'] = 'http://localhost' response["Access-Control-Allow-Headers"]="Content-Type" response["Access-Control-Allow-Origin"] = "http://localhost:8080" return response
  • Step two: add middleware registered in the configuration file in settings.py

    MIDDLEWARE = [
        'app01.my_middleware.CorsMiddleware',  # 在第一行写是因为django中间件的执行顺序,process_response倒序执行
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]

Guess you like

Origin www.cnblogs.com/xinghaonan/p/12072663.html