[Django]-Django + jQuery: Why CSRF verification fails on multiple simultaneous requests

0👍

Problem solved – I missed the fact that the js script responsible for the ajax call set the ‘disabled’ attribute on the form inputs (including the csrf token) in the beforeSend function – such disabled attrs are not sent in POST.

👤fjern

0👍

I think problem in your code. Just read django code


Error catched in this block.

if not constant_time_compare(request_csrf_token, csrf_token):
            logger.warning('Forbidden (%s): %s',
                           REASON_BAD_TOKEN, request.path,
                extra={
                    'status_code': 403,
                    'request': request,
                }
            )
            return self._reject(request, REASON_BAD_TOKEN)

So you front end script send csrf_token which and cookies (which send browser) are not equal


Next code work

tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>

<a href="javascript:" class="req1">req1</a>
<a href="javascript:" class="req2">req2</a>
<br>

<form id="foo" action="" method="POST">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){

        $('.req2').click(function(){
            var form1 = $.post( '', $('#foo').serialize(), function(data){console.log(data)} );
        })

        $('.req1').click(function(){
            var form1 = $.post( '', $('#foo').serialize(), function(data){console.log(data)} );
        })
    })
</script>
</body>
</html>

view

from django import forms
from django.http import HttpResponse

from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect


class TestForm(forms.Form):
    test_field = forms.CharField()


@csrf_protect
def home(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            return HttpResponse('all ok')
    else: form = TestForm()

    return render(request,
        'page.html',
            {
            'form': form,
             },
    )
👤b1_

Leave a comment