S
S
Sergey Nizhny Novgorod2017-03-27 13:45:43
Django
Sergey Nizhny Novgorod, 2017-03-27 13:45:43

Why does csrf swear at an anonymous user?

Hello.
Logic:
1) An anonymous user writes
2) An account is created for him on the fly, which is authenticated and logged in.
3) A post is automatically created on his behalf.
4) There is a chat update cycle via ajax - its dialog is displayed.
If a previously authorized user writes to the chat, then everything goes without problems, and if anonymous, then at step 4 there is a CSRF error. Moreover, if you compare, then the CSRF token is the same at all steps. The code was trimmed a bit so as not to create a bunch of internal output conditions.
The code for creating an anonymous user and posting on his behalf:

def chatpost(request):
    token = {}
    token.update(csrf(request))
    if request.user.is_authenticated():
        ....
    if request.user.is_anonymous():        
        username = randonname
        password = randompass
        email = randomemail

        user = User.objects.create_user(username=username, password=password, email=email)
        user = auth.authenticate(username=username, password=password)
        auth.login(request, user)

        current_user = request.user

        if request.POST:
                    chat_obj = Chat2Model(topic=topic, author=current_user, chattext=chattext)
                    chat_obj.save()

                    json = {}
                    return JsonResponse(json, safe=False, )

Ajax code:
<script async>

    $('#form_chat').submit(function (e) {
        e.preventDefault();
        var m_chatcom ...
        var m_topic ...

        $.ajax({
            type: "POST",
            url: '/chat/post',
            data: {
                "chatcom": m_chatcom,
                "csrfmiddlewaretoken" : "{{ csrf_token }}",
                "topic": m_topic,
            },
            success: function (data) {

                if (data) {
                }
                else {
                }
            }
        });
    });

</script>

(If you refresh the page manually, then the user is displayed as authorized, and messages appear - that is, this code works correctly).
Update code - chat output:
def chatupdate(request):
    if request.POST:

        ... логика выбора нужные чатов, csrf токен и user никак не затрагиваются

        json = {
            "pickup_handler": pickup_handler,
            "break_handler": break_handler,
            "last_chat_pickup": last_chat_pickup,
            "last_chat_break": last_chat_break,
        }

        return JsonResponse(json, safe=False)

<script type="text/javascript">

    function chat(){

        .... - взятие переменных id


        $.ajax({
            type: "POST",
            url: '/chat/update',
            data: {
                "csrfmiddlewaretoken" : "{{ csrf_token }}",
                "m_break": m_break,
                "m_pickup": m_pickup,
                },
            success: function (data) {

                if (data) {
                    $('#new_chat_break').append(data.break_handler);
                    $('#new_chat_pickup').append(data.pickup_handler);

                    var pstr = data.pickup_handler;
                    var bsrt = data.break_handler;

                    }
                else {
                }
                }
            });
        }

    setInterval('chat()', 10000);

</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Neoliz, 2017-03-29
@timofeydeys

For requests with sending data, it is necessary to correctly form the header, namely, set the X-CSRFToken: {{ csrf_token }} header in ajax requests. More is written here: https://www.djbook.ru/rel1.9/ref/csrf.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question