Django form to prevent three kinds of solutions csrf

Solution 1:

When Django enabled by default to prevent csrf (cross-site request forgery) attacks upon request post, not uploaded csrf field, causing the check fails, reported 403 errors

MIDDLEWARE = [
# 'django.middleware.csrf.CsrfViewMiddleware',
]

Comment out this code, you can.

Cons: cause Django project completely unable to prevent attacks csrf

Solution 2:

In views.py file

#导入,可以使此次请求忽略csrf校验
from django.views.decorators.csrf import csrf_exempt

#在处理函数加此装饰器即可
@csrf_exempt
def post(request):
     name=request.post['name']
     return HttpResponse('welcome!{}'.format(name))

Cons: csrf led to the request can not prevent attacks, but much better than the first one kind

Solution 3:

csrf safety django sequence is: Get start background csrf_tokenand sends the front end, and the distal end is performed when the form is submitted form, with the name csrfmiddlewaretoken, is csrf_tokentransmitted together with check fields to the rear end.

This solution is therefore in accordance with this logic, through an interface to obtain csrf_token, in the form and submit a form with a rear end of the check
in views.py

from django.template.context_processors import csrf

def get_csrf(request):
        #生成 csrf 数据,发送给前端
    x = csrf(request)
    csrf_token = x['csrf_token']
    return HttpResponse('{} ; {}'.format(str(re), csrf_token))

Then add another POST request parameter named: csrfmiddlewaretoken function returns a value get_csrf csrf_token, this check will be successful

Advantages: safety check completed csrf

Guess you like

Origin www.cnblogs.com/flyhgx/p/11277634.html