Django study notes 4-csrf protection

1.CSRF verification failed. The request was interrupted.

The reason is django's protection against cross-site attacks when the user submits the form

What is CSRF 

CSRF, Cross Site Request Forgery, Cross Site Request Forgery. For example, if a malicious website has a link to yours, if

A user has logged in to your website, then when the user clicks the link on the malicious website, a request will be sent to your website,

Your website will think that the request is sent by the user himself, but in fact, the request is forged by the malicious website. A malicious website mimics your login page,

The user is fooled, fills in the login information, clicks the submit button, and the malicious website logs in to your web page instead of the user, so that the user information can be modified, or the value in the cooking can be obtained.

CSRF protection mechanism provided by Django

When django responds to a request from a client for the first time, it will randomly generate a token on the server side and put this token in a cookie. Then every POST request will bring this token,

This avoids CSRF attacks.

  • In the returned HTTP response cookie, django will add a csrftoken field for you, the value of which is an automatically generated token
  • In all POST forms, a csrfmiddlewaretoken field must be included (just add a tag to the template, django will automatically generate it for you, see below)
  • Before processing a POST request, django will verify that the value of the csrftoken field in the request's cookie is the same as the value of the csrfmiddlewaretoken field in the submitted form. If it is the same, it indicates that this is a legitimate request, otherwise, this request may come from someone else's csrf attack, returning 403 Forbidden.
  • In all ajax POST requests, add an X-CSRFTOKEN header whose value is the value of the csrftoken in the cookie

How to use CSRF protection in Django

  • First of all, the most basic principle is: GET requests should not have side effects. This means that any code that handles a GET request must have "read-only" access to the resource.
  • To enable django.middleware.csrf.CsrfViewMiddleware this middleware
  • Again, add a {% csrf_token %} tag to all POST form elements
  • When rendering modules, use RequestContext. RequestContext will process the csrf_token tag, thus automatically adding an input named csrfmiddlewaretoken to the form

E.g:

1.{% csrf_token %}

django.template import RequestContext

return render(req,'df_user/login.html',context_instance=RequestContext(req))。

2. Comment out the django project settings.py     #'django.middleware.csrf.CsrfViewMiddlewar

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325623302&siteId=291194637