


Explanation 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>1932 33
34
GET属性
35 一键传一值3637 一键传多值38 39
40
JsonResponse
41 ajax42 4344
Cookie
45 设置Cookie4647 获取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 = $('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'] + '');17 ul.append('<li>' + data['h2'] + '');18 ul.append('<li>' + data['method'] + '');19 ul.append('<li>' + data['csrf'] + '');20 ul.append('<li>' + data['data'] + '');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 = $('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'] + '');18 ul.append('<li>' + data['h2'] + '');19 ul.append('<li>' + data['method'] + '');20 ul.append('<li>' + data['csrf'] + '');21 ul.append('<li>' + data['data'] + '');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>3952 53
54
GET属性
55 一键传一值5657 一键传多值58 59
60
JsonResponse
61 ajax62 6364
Cookie
65 设置Cookie6667 获取Cookie68 69
70
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!

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

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.

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.

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 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.

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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
