Automated Operations Python series Django CSRF cross-site request forgery, middleware

Source: Internet
Author: User

Csrf

CSRF, cross-site request forgery is a way to hijack a user to perform a non-intended attack on a Web site application that is currently logged on, in short, an attacker who deceives a user's browser with some technical means to access a website that he has authenticated and performs some actions (such as sending an email, sending a message, Even property operations such as transfer and purchase of goods).

Django's CSRF middleware validation can effectively eliminate this kind of malicious attack, the principle is Django in the authentication request through the client to do another encryption verification, the encryption method only Django own know, The client will deny access even if it carries the session anti-decryption CSRF, which is a necessary step in the Django life request cycle, so we can also elicit the concept of middleware and the general use of custom middleware.

Turn on CSRF validation in setting

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/8E/A7/wKioL1jIANrSCS3cAAHlMg-QgZo113.png "title=" 4.png "alt=" Wkiol1jianrscs3caahlmg-qgzo113.png "/>

CSRF verification information carried by the browser after opening

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M00/8E/A8/wKiom1jIAPzh7dEmAAGFS-c5MIQ295.png "title=" 5.png "alt=" Wkiom1jiapzh7demaagfs-c5miq295.png "/>

Since global CSRF authentication is turned on, Django will require validation for each page post request that we submit, so we have to load the configuration information on the page in 2 ways

1) front page submit directly

<form action= "/login/" method= "POST" >//Add template information to the from form {% Csrf_token%} <input type= "text" name= "user" /> <input type= "text" name= "pwd"/> <input type= "Submit" value= "Submit"/></form>

2) Ajax Submissions

$ (function () {    //  This is the Ajax global event   before an AJAX request is made     $.ajaxsetup ({         beforesend: function (xhr,settings) {             xhr.setrequestheader (' X-csrftoken ',  $.cookie (' Csrftoken '));         }    });       $ (' #btn1 '). Click (function  ()  {        $. Ajax ({            url:  '/login/',             type: "GET",             data: {' user ':  ' root ',  ' pwd ':  ' 123 '},             //  add csrftoken  to the request header if the AJAX global bindings are already set above   Can omit             // headers: {' X-csrftoken ':  $.cookie (' CSRFtoken ')},            success:function (ARG) {             }        } ) (&NBSP;&NBSP;&NBSP;&NBSP;});})

Backstage we can get through X-csrftoken

# Print (Settings. Csrf_header_name) # http_x_csrftoken# X-csrftoken

After enabling CSRF in the middleware, it means that the global view function will be required to verify that if there is a need for a few page views, you can add the following adorner

Cancel CSRF Verification Protection @csrf_exemptdef Index (Request)://Open CSRF Authentication Protection @csrf_protectdef Index (request) separately:

Middleware

The middleware in Django, in fact, is a class, and after the request arrives and ends, Django executes the appropriate method in the middleware according to its own rules, as shown above in the middleware that we see is the one in Django that is already registered with the middleware

1) Custom Middleware

In the middleware we can customize 5 ways

1) Accept the request method Process_request (Self,request)//2) Accept the View method Process_view (self, request, callback, Callback_args, Callback_ Kwargs)//3) Determine if the return function has a Render method Process_template_response (Self,request,response)//4) Exception handling method Process_exception (self, Request, exception)//5) Reply requests process_response (self, request, response)

Build the middleware directory middle in the app sibling directory, create a new middleware file m1.py

From django.utils.deprecation import middlewaremixinfrom django.shortcuts import  HttpResponse//  definition class  need to inherit Middlewaremixinclass row1 (Middlewaremixin):     def process_request (self,request):         print (' Request_ Row_1 ')      def process_view (self, request, view_func, view_func_ Args, view_func_kwargs):         print (' view_row_1 ')       def process_response (Self, request, response):         print (' process_row_1 ')         return response  class row2 (middlewaremixin):     def process_request (self,request):         print (' request_row_2 ')      def process _view (Self, request, view_func, view_func_args, view_func_kwargs):         Print (' view_row_2 ')      def process_response (self, request, response):         print (' process_row_2 ')          return response

Register the middleware in setting, pay attention to our placement, run the program let's see what the order of the Django middleware is

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/8E/A7/wKioL1jIAReT0ItOAAHE37ZW03A230.png "title=" 6.png "alt=" Wkiol1jiaret0itoaahe37zw03a230.png "/>

Routing URL Configuration

urlpatterns = [url (r ' ^test/(? p<nid>\d+) $ ', views.test),]

Views View function Configuration

def test (Request,nid): Print (' View--') return render (Request, ' index.html ')

Run results

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/8E/A8/wKiom1jIASbji6E8AADYZDsEJEI844.png "title=" 7.png "alt=" Wkiom1jiasbji6e8aadyzdsejei844.png "/>

So the process of running the middleware is actually as shown

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/8E/A7/wKioL1jIATbCP_OiAAGk1CYIYvg530.png "title=" 8.png "alt=" Wkiol1jiatbcp_oiaagk1cyiyvg530.png "/>

When Django receives a user request, it is processed by the middleware in turn, through the request method, and so on to the last middleware, after a route matching to find the function of the view, go back to execute the view method of each middleware, the request carries the additional parameters are encapsulated in View_ In the func parameter, the data is returned by the server-side views view function, and the middleware passes the message to the user via reponse.

At this point the role of the middleware is very obvious, you can do before the request really arrives at the server backend, such as interception operations

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M02/8E/A8/wKiom1jIAUrAgBq1AAGpHHGpuWM681.png "title=" 9.png "alt=" Wkiom1jiauragbq1aagphhgpuwm681.png "/>

If the request is intercepted in the middleware row_2, just return the HttpResponse information directly

Class Row2 (middlewaremixin): def process_request (self,request): Print (' request_row_2 ') return httprespons E (' Row_2_no ... ')

At this point we look at the middleware execution process, the request has been intercepted in the Row_2 middleware, and did not reach the server backend views

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/8E/A7/wKioL1jIAV2AXZA_AADhwhf_U9Y743.png "title=" 10. PNG "alt=" Wkiol1jiav2axza_aadhwhf_u9y743.png "/>

Exception handling

If the service side of the Views function exception, general Django will directly error to the user interface, which is not friendly to the user, so we can in the middle layer to face some abnormal interception, and processing

def test (Request,nid): Print (' View-to ')//analog processing exception i = Int (' abc ') Return render (Request, ' index.html ')

Editing middleware functions

Class Row2 (middlewaremixin): ...//row_2 add exception Handling Def process_exception (self, request, exception): If Isin Stance (Exception, valueerror): Return HttpResponse (' data processing exception occurred. ‘)

Interface display

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/8E/A7/wKioL1jIAW_yT1MbAAB2g7P3nw0078.png "title=" 11. PNG "alt=" Wkiol1jiaw_yt1mbaab2g7p3nw0078.png "/>




This article comes from the "change from every day" blog, so be sure to keep this source http://lilongzi.blog.51cto.com/5519072/1906558

Automated Operations Python series Django CSRF cross-site request forgery, middleware

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.