Django POST request due to open prevent CSRF, 403 error, and four ways to resolve

Source: Internet
Author: User

Django Default on Prevent CSRF (cross-site request forgery) attacks, when the post request, did not upload the csrf field, resulting in a checksum failure, reported 403 error

Workaround 1:

Comment out this code, you can.

Cons: Causing Django projects to completely prevent CSRF attacks

Workaround 2:

In the views.py file

#导入, you can make this request ignore the CSRF check from DJANGO.VIEWS.DECORATORS.CSRF import csrf_exempt# in the handler function plus this adorner @csrf_exemptdef  Post (Request):     name=request.post[' name ']     return HttpResponse (' welcome!{} '. Format (name))   

Cons: This request does not prevent CSRF attacks, but is much better than the first

Workaround 3:

MTV mode developed for use with templates, added in template file Submission form code

But I do not use MTV mode for development, only use the restful mode, so for the RESTFU mode development, the use of the fourth solution.

Workaround 4:

Django's CSRF safe working order is to get csrf_token from the background and send it to the front end, and then send the field with a value of Csrf_token named Csrfmiddlewaretoken to the backend for validation when the form form is submitted.

So this solution is to follow this logic, first get csrf_token through an interface, and then submit it to the backend checksum in form form

From django.template.context_processors import csrfdef get_csrf (Request):        #生成 csrf data, sent to front end    x =  CSRF (Request)    Csrf_token = x[' Csrf_token ']    return HttpResponse (' {}; {} '. Format (str (re), Csrf_token))   

Then add the parameter named: Csrfmiddlewaretoken value to the Csrf_token returned by the GET_CSRF function in another POST request, so the checksum succeeds

Advantages: Complete the CSRF safety check

Django POST request due to open prevent CSRF, 403 error, and four ways to resolve

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.