Django middleware - CSRF -Auth pluggable module configuration implemented -seettings

--- --- restore content begins

Django middleware

First, what is the middleware

  django django middleware is similar to security; when the request needs to go through middleware, to reach django backend (url, views, models, templates),

In response, we also need to go through middleware to reach the web server gateway interface;

Positioned intermediate between the web server and the routing layer url; is interposed between a processing request and response processing.

Second, what is the use of middleware

  If you want to modify the request, for example, is transferred to the HttpRequest object in view. Or if you want to change the view return HttpResponse object, which can be achieved through the middleware.

What can be used to do?

  1, the site's global identity verification, access frequency limit inspection authority; it comes to the global verification can be achieved with middleware

  2, Django middleware web frames are all doing the best

 

Django's default middleware :( django project in the settings module, there is a variable MIDDLEWARE_CLASSES, where each element is a middleware)

django default middleware seven below:

 

 Third, custom middleware

  The method defines five middleware; is mainly (process_request: Request and process_response: return)

1、process_request(self,request)

2、process_view(self, request, callback, callback_args, callback_kwargs)

3、process_template_response(self,request,response)

4、process_exception(self, request, exception)

5、process_response(self, request, response)

  The return value of the above method may be None or a HttpResponse object , if it is None, continuing rearwardly Django proceed according to the rules defined above,

If HttpResponse object, the object is returned directly to the user.

1、process_request和process_response

  When the user initiated the request will sequentially go through all the intermediate, process_request request this time, and finally to function views, the rear views of a function, sequentially passing through the intermediate, this time is process_response, and finally returned to the requester By.

As shown below, a full flow of intermediate:

 

2, complete Djang start life cycle:

3, middleware required to master the method of focus:

  . 1, .process_request () method

    law:

      1, when the request will go through each of the intermediate process_request inside (top to bottom) () method

      2, if it was HttpResponse object, it will return to direct, no longer performed down; you can do based on this characteristic frequency of access restrictions, identity verification, checking permissions, etc.

  

  2, process_response () method

   law:

    (1) it must be returned response parameter, because this parameter is to refer to the data to be returned to the front end.

    (2), take the time to respond, in turn through each broker inside process_response method (bottom-up)

Methods need to know:

    (1)、process_view() :

            Triggered before routing to match the successful implementation of the view function

    (2)、process_exception() :

            When you view function will automatically perform error

    (3)、process_template_response() 

            When you return to the HttpResponse object must contain render attributes will trigger

 

 4, custom middleware, write the class must inherit  MiddlewareMixin

 

 (1) Step 1: Import

from django.utils.deprecation import MiddlewareMixin

 

 (2), custom middleware, the new file writing member

from django.utils.deprecation import MiddlewareMixin#
from django.shortcuts import HttpResponse
#
class Md1(MiddlewareMixin):
#
    def process_request(self,request):
        print("Md1请求")
 #
    def process_response(self,request,response):
        print("Md1返回")
        return response
#
class Md2(MiddlewareMixin):
#
    def process_request(self,request):
        print("Md2请求")
        #return HttpResponse("Md2中断")
    def process_response(self,request,response):#
        print("Md2返回")
        return response

 (3): a view of view defined function (index) in the views

def index(request):

    print("view函数...")
    return HttpResponse("OK")

 

(4) registered in their definition of middleware MIDDLEWARE settings.py's

1. If you want your writing middleware to take effect, it must first inherit MiddlewareMixin 
2. When registering a custom middleware, make sure not to wrong path

The results (5) View running: results summarized above law

Request law derived:

The law of return obtained:

The second case, when the middleware kind custom has HttpRsponse, direct return:

(6) If there is no response returned parameter, because this parameter is to refer to the front end of the return data

 

 The results show an error:

 

 (7) other methods to understand:

1、process_view

  The method takes four parameters

process_view(self, request, view_func, view_args, view_kwargs)

 

Example:

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,redirect,render,reverse

class Md1(MiddlewareMixin):
    def process_request(self,request):
        print('Md1请求')
        return HttpResponse("Md1中断")

    def process_response(self,request,response):
        print('Md1返回')
        return response
        # return HttpResponse("嘿嘿!")

    def process_view(self,request,callback,callback_args,callback_kwargs):
        print('Md1views')

class Md2(MiddlewareMixin):
    def process_request(self,request):
        print("Md2请求")
        return HttpResponse('Md2中断')

    def process_response(self,request,response):
        print('Md2返回')
        return response

    def process_view(self,callback,callback_args,callback_kwargs):
        print("Md2views")

 

2, process_exception, the method two parameters:

process_exception(self, request, exception)

 

An HttpRequest object

Exception exception is a view of an object produced by an abnormal function.

3、process_template_response(self,request,response)方法:

  This method returns a value required by the function of view, must be an object class containing render method, this method will perform

Summary: You just have parameter repsonse when you're writing middleware feels that she returned this reponse is to give the front end of the message

 Two, CSRF_TOKEN CSRF

  1. What is csrf

  CSRF (Cross-site request forgery) cross-site request forgery, also referred to as "One Click Attack" or Session Riding;

Simple to understand: that the attacker stole your identity, send a malicious request to you in the name of the server for this request is perfectly legitimate;

To complete a CSRF attack, the victim must complete two steps in sequence:

  1. Log in to trusted sites A, and generates Cookie locally.
  2. In the case of A is not out of, access to dangerous websites B.

Simple example phishing sites:

Regular site:

views.py

def transfer(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        money = request.POST.get('money')
        target_user = request.POST.get('target_user')
        print('%s 给 %s 转了 %s元'%(username,target_user,money))
    return render(request,'res.html')

 

res.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h2>这是正儿八经的网站</h2>
<form action="//" method="post">
{#    {% csrf_token %}#}
    <p>本人用户名:<input type="text" name="username"></p>
    <p>转账金额:<input type="text" name="money"></p>
    <p>对方账户:<input type="text" name="target_user"></p>
    <input type="submit">
</form>

Phishing sites break principle:

  In other accounts allow users to input the input above tricks, like writing a viewx.py, routing and url,

Modify the front end HTML content to let users transfer each other's hidden binding value = 'jason', modify the port at startup.

 

 Ideas to prevent phishing sites:

  The site will return a user's form form page, thiophene secretly a random string, to the time the request,

Will first than random strings are the same, if not directly reject (403)

The random string has the following characteristics:

  1, the same browser is not the same without a visit

  2, will not be repeated across different browsers

Cross-site request forgery solution:

. 1, form TABLE post request sending time, only you need to write a word

  {% csrf_token %}

Writing {% csrf_token%}, will generate a pair of key-value pairs in the client

2, when the post request by sending AJAX, check how to avoid csrf

  (1) Now write the page {% csrf_token%}, using the tag lookup, to obtain the key information input, keyword: 'csrfmiddlewaretoken '

{'username':'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}

 

   (2) direct writing '{{csrf_token}}'

{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'}

 

  (3), you can get the random key-value pairs, wrote a js file, then just import the file to use.

Add to settings.Py static in:

 

 Html page is then used at the front end is introduced:

 

Writing static files stored JS code: The following code is provided by the official, quoted in the place you want to use after writing to:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');


function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

 

 

 

 

 

  

 

 

 

 

--- end --- restore content

Guess you like

Origin www.cnblogs.com/Gaimo/p/11588026.html