search
HomeWeb Front-endJS TutorialExplanation of knowledge points about the same origin policy and CSRF security policy

Although I have been doing web development for a while, I have never had a deep understanding of the same-origin policy and csrf security policy, so I took the time to do a simple experiment to understand it. The experimental process is as follows, share it with everyone.

Experiment purpose: to verify the relationship and difference between the same-origin policy and the csrf security policy

Experimental plan: 1. Linux builds a python server of the django framework (a); Windows builds a simple js server (b)
            2. The homepage of b has the following content: (1) Passed Submit a form to a through post\get method When the CSRF security policy is not turned on, open the homepage of B. The page of B can submit the form to A normally through the post\get method and get the reply page; however, the data of A cannot be requested through the get\post method of ajax. Observing the log of a, it is found that the request of b can be received on a, but the data attached to the request of b cannot be loaded successfully. The ajax (get\post) request of b can get the response of a, and it is sent to open B's browser reported a same-origin policy warning.
2. When a opens the CSRF security policy, open the homepage of b. The page of b can submit the form to a normally through the get method and get the reply page, but it cannot submit through the post method. ; Page b cannot request the data of a through the get\post method of ajax.

Conclusion: 1. Same-origin policy: The js language is designed for security considerations and only allows same-origin access. Non-original access can also send requests to the corresponding server, but all data attached to the browser request will be lost, and the server can return the response of the request. However, there will be a same-origin policy warning during the response phase when the browser parses the response issued by the server. (Explanation of ajax technology based on js)
2. CSRF security policy: Security considerations when building a server require ordinary developers to carry out relevant designs (frameworks generally come with the design of CSRF security policies). The csrf policy process is: when requesting a page from the server, the server's response will set a cookie to the browser. When a post form is submitted to the server, the cookie set by the server will be appended to the browser's request and submitted together. When receiving the request, it will be verified whether the attached cookie is correct (each user's communication connection with the server has only one unique cookie. After the connection is interrupted, the server will set a new cookie to the browser the next time the connection is made). Only the cookie verification passes. Only then can the correct response be issued. If the verification fails, a "403" error code will be issued.


  1 # --------------Django服务器部分代码--------------  2 # -*- coding:utf-8 -*-  3 from django.shortcuts import render  4 from django.http import HttpResponse, HttpResponseRedirect, JsonResponse  5   6 # Create your views here.  7   8   9 def index(request): 10  11     context = {'contents': 'hello world'} 12     # return HttpResponse("ok") 13     response= render(request, 'booktest/index.html', context) 14     return response 15  16  17 def args(request, id1, id2): 18  19     string = '%s--%s' % (id1, id2) 20     return HttpResponse(string) 21  22  23 def get1(request): 24  25     mode = request.encoding 26     dict = request.GET 27     a = dict.get('a') 28     b = dict.get('b') 29     c = dict.get('c') 30     string = 'method:%s--%s--%s--%s' % (mode, a, b, c) 31     return HttpResponse(string) 32  33  34 def get2(request): 35  36     dict = request.GET 37     a = dict.getlist('a') 38     b = dict.get('b') 39     c = dict.get('c') 40     d = dict.get('d', 'have no') 41     string = '%s--%s--%s--%s' % (a, b, c, d) 42     return HttpResponse(string) 43  44  45 def post(requst): 46  47     str_data = '---%s---%s' % (requst.method, requst.POST.get('uname')) 48  49     return HttpResponse(str_data) 50  51  52 def get3(request): 53  54     dict = request.GET 55     a = dict.get('a') 56     b = dict.get('b') 57     c = dict.get('c') 58     context = {'1': a, '2': b, '3': c} 59     # return HttpResponse("ok") 60     return HttpResponse(context) 61     # return render(request, 'booktest/get1.html', context) 62  63  64 def get4(request): 65  66     return HttpResponseRedirect('/admin/') 67  68  69 def ajax(request): 70  71     # return HttpResponse('ok') 72     return render(request, 'booktest/ajax.html/') 73  74  75 def json(request): 76  77     data1 = request.POST.get('csrfmiddlewaretoken') 78     data2 = request.POST.get('data') 79     print('------------%s------------%s---' % (data1, data2)) 80     a = {'h1': 'hello', 'h2': 'world', 'method': request.method, 'csrf': data1, 'data': data2} 81  82     return JsonResponse(a) 83  84  85 def cookie_set(request): 86     print('123') 87     cookie_value = 'hello' 88  89     response = HttpResponse("<h1 id="设置Cookie-请查看响应报文头">设置Cookie,请查看响应报文头</h1>") 90     # response = HttpResponse("hello") 91 # Cookie中设置汉字键值对失败 92     response.set_cookie('h1', cookie_value) 93     # return HttpResponse('ok') 94     return response 95  96  97 def cookie_get(request): 98  99     response = HttpResponse('<h1 id="读取Cookie-数据如下-br-cookies-request-COOKIES-if-cookies-get-h-response-write-h-cookies-h">读取Cookie,数据如下:<br>')100     cookies = request.COOKIES101     if cookies.get('h1'):102         response.write('<h1>'+cookies['h1']+'</h1>')103 104     return response</h1>

 1  2  3 nbsp;html> 4  5  6     <meta> 7     <title>index</title> 8  9 10 {#    <input>#}11     <a>返回主页</a>12 13     <hr>14     <h1 id="参数">参数</h1>15     <a>get一键传一值</a>16     <br>17     <a>get一键传多值</a>18     <br><br>19     
20 21     {% csrf_token %}22 23     姓名:
24     密码:
25     性别:男26     
27     爱好:胸口碎大石28     脚踩电灯炮29     口吐火
30     31     
32 33     
34     

GET属性

35     一键传一值36     
37     一键传多值38 39     
40     

JsonResponse

41     ajax42 43     
44     

Cookie

45     设置Cookie46     
47     获取Cookie48 49 

 1  2  3 nbsp;html> 4  5  6     <meta> 7     <title>ajax</title> 8  9 <script></script>10 <script>11         $(function () {12             data1 = $(&#39;input[name="csrfmiddlewaretoken"]&#39;).prop(&#39;value&#39;);13             $(&#39;#btnjson&#39;).click(function () {14                 $.post(&#39;/json/&#39;, {&#39;csrfmiddlewaretoken&#39;:data1,&#39;data&#39;:&#39;Hi Hellow&#39;}, function (data) {15                     ul = $(&#39;#jsonlist&#39;);16                     ul.append(&#39;<li>&#39; + data[&#39;h1&#39;] + &#39;&#39;);17                     ul.append(&#39;<li>&#39; + data[&#39;h2&#39;] + &#39;&#39;);18                     ul.append(&#39;<li>&#39; + data[&#39;method&#39;] + &#39;&#39;);19                     ul.append(&#39;<li>&#39; + data[&#39;csrf&#39;] + &#39;&#39;);20                     ul.append(&#39;<li>&#39; + data[&#39;data&#39;] + &#39;&#39;);21                 })22             });23         })24     </script>25 26 27     <div>hello world!</div>28     {% csrf_token %}29     <input>30     
    31 32 

     1  2  3 nbsp;html> 4  5  6     <meta> 7     <title>index</title> 8      9     10     <script></script>11     <script>12         $(function () {13             data1 = $(&#39;input[name="csrfmiddlewaretoken"]&#39;).prop(&#39;value&#39;);14             $(&#39;#btnjson&#39;).click(function () {15                 $.get(&#39;http://192.168.27.128:8000/json/&#39;, {&#39;csrfmiddlewaretoken&#39;:data1,&#39;data&#39;:&#39;HiHellow&#39;}, function (data) {16                     ul = $(&#39;#jsonlist&#39;);17                     ul.append(&#39;<li>&#39; + data[&#39;h1&#39;] + &#39;&#39;);18                     ul.append(&#39;<li>&#39; + data[&#39;h2&#39;] + &#39;&#39;);19                     ul.append(&#39;<li>&#39; + data[&#39;method&#39;] + &#39;&#39;);20                     ul.append(&#39;<li>&#39; + data[&#39;csrf&#39;] + &#39;&#39;);21                     ul.append(&#39;<li>&#39; + data[&#39;data&#39;] + &#39;&#39;);22                 })23             });24         })25     </script>26     27     28 29 30 {#    <input>#}31     <a>返回主页</a>32 33     <hr>34     <h1 id="参数">参数</h1>35     <a>get一键传一值</a>36     <br>37     <a>get一键传多值</a>38     <br><br>39     
    40 41     {% csrf_token %}42 43     姓名:
    44     密码:
    45     性别:男46     
    47     爱好:胸口碎大石48     脚踩电灯炮49     口吐火
    50     51     
    52 53     
    54     

    GET属性

    55     一键传一值56     
    57     一键传多值58 59     
    60     

    JsonResponse

    61     ajax62 63     
    64     

    Cookie

    65     设置Cookie66     
    67     获取Cookie68     69     
    70     
    hello world!
    71     {% csrf_token %}72     73     
      74 75 

      The above is the detailed content of Explanation of knowledge points about the same origin policy and CSRF security policy. For more information, please follow other related articles on the PHP Chinese website!

      Statement
      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
      Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

      Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

      Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

      The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

      The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

      JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

      Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

      JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

      The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

      The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

      Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

      Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

      Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

      Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

      JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

      JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

      See all articles

      Hot AI Tools

      Undresser.AI Undress

      Undresser.AI Undress

      AI-powered app for creating realistic nude photos

      AI Clothes Remover

      AI Clothes Remover

      Online AI tool for removing clothes from photos.

      Undress AI Tool

      Undress AI Tool

      Undress images for free

      Clothoff.io

      Clothoff.io

      AI clothes remover

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      WebStorm Mac version

      WebStorm Mac version

      Useful JavaScript development tools