Home  >  Article  >  Web Front-end  >  Explanation of knowledge points about the same origin policy and CSRF security policy

Explanation of knowledge points about the same origin policy and CSRF security policy

巴扎黑
巴扎黑Original
2017-07-23 14:27:371500browse

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>设置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>读取Cookie,数据如下:<br>')100     cookies = request.COOKIES101     if cookies.get('h1'):102         response.write('<h1>'+cookies['h1']+'</h1>')103 104     return response

 1 <--Django服务器template部分的index.html代码--> 2  3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6     <meta charset="utf-8"> 7     <title>index</title> 8 </head> 9 <body>10 {#    <input type="button" value="返回">#}11     <a href="/">返回主页</a>12 13     <hr>14     <h1>参数</h1>15     <a href="/get1/?a=1&b=2&c=3">get一键传一值</a>16     <br>17     <a href="/get2/?a=1&b=2&c=3&a=5">get一键传多值</a>18     <br><br>19     <form method="post" action="/post/">20 21     {% csrf_token %}22 23     姓名:<input type="text" name="uname"/><br>24     密码:<input type="password" name="upwd"/><br>25     性别:<input type="radio" name="ugender" value="1"/>男26     <input type="radio" name="ugender" value="0"/>女<br>27     爱好:<input type="checkbox" name="uhobby" value="胸口碎大石"/>胸口碎大石28     <input type="checkbox" name="uhobby" value="脚踩电灯炮"/>脚踩电灯炮29     <input type="checkbox" name="uhobby" value="口吐火"/>口吐火<br>30     <input type="submit" value="提交"/>31     </form>32 33     <hr>34     <h1>GET属性</h1>35     <a href="/get3/?a=1&b=2&c=3">一键传一值</a>36     <br>37     <a href="/get4/?a=1&b=2&c=3&a=5">一键传多值</a>38 39     <hr>40     <h1>JsonResponse</h1>41     <a href="/ajax/">ajax</a>42 43     <hr>44     <h1>Cookie</h1>45     <a href="/cookie_set/">设置Cookie</a>46     <br>47     <a href="/get_Cookie/">获取Cookie</a>48 </body>49 </html>

 1 <--Django服务器ajax.html代码--> 2  3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6     <meta charset="UTF-8"> 7     <title>ajax</title> 8  9 <script src="/static/js/jquery-1.12.4.min.js?1.1.11"></script>10 <script>11         $(function () {12             data1 = $('input[name="csrfmiddlewaretoken"]').prop('value');13             $('#btnjson').click(function () {14                 $.post('/json/', {'csrfmiddlewaretoken':data1,'data':'Hi Hellow'}, function (data) {15                     ul = $('#jsonlist');16                     ul.append('<li>' + data['h1'] + '</li>');17                     ul.append('<li>' + data['h2'] + '</li>');18                     ul.append('<li>' + data['method'] + '</li>');19                     ul.append('<li>' + data['csrf'] + '</li>');20                     ul.append('<li>' + data['data'] + '</li>');21                 })22             });23         })24     </script>25 </head>26 <body>27     <div>hello world!</div>28     {% csrf_token %}29     <input type="button" id="btnjson" value="获取json数据">30     <ul id="jsonlist"></ul>31 </body>32 </html>

 1 <--JS搭建的服务器首页代码--> 2  3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6     <meta charset="utf-8"> 7     <title>index</title> 8      9     10     <script src="/js/jquery-1.12.4.min.js?1.1.11"></script>11     <script>12         $(function () {13             data1 = $('input[name="csrfmiddlewaretoken"]').prop('value');14             $('#btnjson').click(function () {15                 $.get('http://192.168.27.128:8000/json/', {'csrfmiddlewaretoken':data1,'data':'HiHellow'}, function (data) {16                     ul = $('#jsonlist');17                     ul.append('<li>' + data['h1'] + '</li>');18                     ul.append('<li>' + data['h2'] + '</li>');19                     ul.append('<li>' + data['method'] + '</li>');20                     ul.append('<li>' + data['csrf'] + '</li>');21                     ul.append('<li>' + data['data'] + '</li>');22                 })23             });24         })25     </script>26     27     28 </head>29 <body>30 {#    <input type="button" value="返回">#}31     <a href="/">返回主页</a>32 33     <hr>34     <h1>参数</h1>35     <a href="/get1/?a=1&b=2&c=3">get一键传一值</a>36     <br>37     <a href="/get2/?a=1&b=2&c=3&a=5">get一键传多值</a>38     <br><br>39     <form method="post" action="http://192.168.27.128:8000/post/">40 41     {% csrf_token %}42 43     姓名:<input type="text" name="uname"/><br>44     密码:<input type="password" name="upwd"/><br>45     性别:<input type="radio" name="ugender" value="1"/>男46     <input type="radio" name="ugender" value="0"/>女<br>47     爱好:<input type="checkbox" name="uhobby" value="胸口碎大石"/>胸口碎大石48     <input type="checkbox" name="uhobby" value="脚踩电灯炮"/>脚踩电灯炮49     <input type="checkbox" name="uhobby" value="口吐火"/>口吐火<br>50     <input type="submit" value="提交"/>51     </form>52 53     <hr>54     <h1>GET属性</h1>55     <a href="/get3/?a=1&b=2&c=3">一键传一值</a>56     <br>57     <a href="/get4/?a=1&b=2&c=3&a=5">一键传多值</a>58 59     <hr>60     <h1>JsonResponse</h1>61     <a href="/ajax/">ajax</a>62 63     <hr>64     <h1>Cookie</h1>65     <a href="/cookie_set/">设置Cookie</a>66     <br>67     <a href="/get_Cookie/">获取Cookie</a>68     69     <hr>70     <div>hello world!</div>71     {% csrf_token %}72     <input type="button" id="btnjson" value="获取json数据">73     <ul id="jsonlist"></ul>74 </body>75 </html>

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