Detail django middleware ES1en. middleware. csrf. CsrfViewMiddleware to prevent csrf attack

  • 2020-12-10 00:47:36
  • OfStack

1. Background processing in django

1, the adding of django setting django. contrib. messages. middleware. MessageMiddleware, 1 new django projects will bring.


MIDDLEWARE_CLASSES = [
  'django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
  'django.contrib.messages.middleware.MessageMiddleware', 
] 

2. Add {% csrf %} to from on html page of templete, and the syntax of background redirection is as follows:


return render_to_response(xxx.html', context_instance=RequestContext(request))

2. Front-end processing

Add the following statement to all ajax requests:


$(function () {
  $.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
  });
})

Such a request to the background would take the csrf_token value generated by django. The middleware csrf module intercepts to determine whether the value of csrf_token is 1, and if 1 sends, the request is valid.

(3) for ajax complex objects, such as [{" id ":" 001 ", "name" : "xiao Ming"}, {" id ":" 002 ", "name" : "small army"}]., background post processing

This object must be converted to json format and sent to the background, where it can be deserialized. (Do not use the other serialization formats of ajax, as deep serialization makes django background parsing more difficult.)

contentType does not need to specify utf-8, otherwise post parsing goes wrong

4. csrf attack and prevention

csrf exploits the timeliness of session and cookie to attack. He gets the requested cookie and makes the request within the session statute of limitations. Therefore, for important information, important functions are processed in a single request. The request is invalidated once.

For example: add token validation information to the request header, and it becomes invalid when used up. csrf_token, the middleware of django, is prevented by this principle.


Related articles: