Home Web Front-end JS Tutorial 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

Jul 23, 2017 pm 02:27 PM
csrf Safety Strategy

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
Copy after login

 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>
Copy after login

 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>
Copy after login

 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>
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Framework Security Guide: How to Prevent CSRF Attacks? PHP Framework Security Guide: How to Prevent CSRF Attacks? Jun 01, 2024 am 10:36 AM

PHP Framework Security Guide: How to Prevent CSRF Attacks? A Cross-Site Request Forgery (CSRF) attack is a type of network attack in which an attacker tricks a user into performing unintended actions within the victim's web application. How does CSRF work? CSRF attacks exploit the fact that most web applications allow requests to be sent between different pages within the same domain name. The attacker creates a malicious page that sends requests to the victim's application, triggering unauthorized actions. How to prevent CSRF attacks? 1. Use anti-CSRF tokens: Assign each user a unique token, store it in the session or cookie. Include a hidden field in your application for submitting that token

Tips for turning off real-time protection in Windows Security Center Tips for turning off real-time protection in Windows Security Center Mar 27, 2024 pm 10:09 PM

In today's digital society, computers have become an indispensable part of our lives. As one of the most popular operating systems, Windows is widely used around the world. However, as network attack methods continue to escalate, protecting personal computer security has become particularly important. The Windows operating system provides a series of security functions, of which "Windows Security Center" is one of its important components. In Windows systems, "Windows Security Center" can help us

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Jun 01, 2024 am 09:26 AM

When implementing machine learning algorithms in C++, security considerations are critical, including data privacy, model tampering, and input validation. Best practices include adopting secure libraries, minimizing permissions, using sandboxes, and continuous monitoring. The practical case demonstrates the use of the Botan library to encrypt and decrypt the CNN model to ensure safe training and prediction.

Security configuration and hardening of Struts 2 framework Security configuration and hardening of Struts 2 framework May 31, 2024 pm 10:53 PM

To protect your Struts2 application, you can use the following security configurations: Disable unused features Enable content type checking Validate input Enable security tokens Prevent CSRF attacks Use RBAC to restrict role-based access

PHP Microframework: Security Discussion of Slim and Phalcon PHP Microframework: Security Discussion of Slim and Phalcon Jun 04, 2024 am 09:28 AM

In the security comparison between Slim and Phalcon in PHP micro-frameworks, Phalcon has built-in security features such as CSRF and XSS protection, form validation, etc., while Slim lacks out-of-the-box security features and requires manual implementation of security measures. For security-critical applications, Phalcon offers more comprehensive protection and is the better choice.

How to enhance the security of Spring Boot framework How to enhance the security of Spring Boot framework Jun 01, 2024 am 09:29 AM

How to Enhance the Security of SpringBoot Framework It is crucial to enhance the security of SpringBoot applications to protect user data and prevent attacks. The following are several key steps to enhance SpringBoot security: 1. Enable HTTPS Use HTTPS to establish a secure connection between the server and the client to prevent information from being eavesdropped or tampered with. In SpringBoot, HTTPS can be enabled by configuring the following in application.properties: server.ssl.key-store=path/to/keystore.jksserver.ssl.k

Which wallet is safer for SHIB coins? (Must read for newbies) Which wallet is safer for SHIB coins? (Must read for newbies) Jun 05, 2024 pm 01:30 PM

SHIB coin is no longer unfamiliar to investors. It is a conceptual token of the same type as Dogecoin. With the development of the market, SHIB’s current market value has ranked 12th. It can be seen that the SHIB market is hot and attracts countless investments. investors participate in investment. In the past, there have been frequent transactions and wallet security incidents in the market. Many investors have been worried about the storage problem of SHIB. They wonder which wallet is safer for SHIB coins at the moment? According to market data analysis, the relatively safe wallets are mainly OKXWeb3Wallet, imToken, and MetaMask wallets, which will be relatively safe. Next, the editor will talk about them in detail. Which wallet is safer for SHIB coins? At present, SHIB coins are placed on OKXWe

See all articles