K
K
Kirill2021-06-15 02:03:59
Django
Kirill, 2021-06-15 02:03:59

How to fix CSRF token invalid after deauth via AJAX?

The title of the question is a curve, but not the point.
In general, on the main page there is authentication through an AJAX post request. It sends mail (as a login), a password to the server and takes a csrf token from the cookie.
Authentication was successful and instead of the form, a block appears with a login, an avatar, a button to go to personal account and a button for deauthentication.
If a person immediately clicks to log out on the server, logout will work and the login and password entry form will appear again. But already when trying to authenticate, the server will throw a csrf token invalid error.
How can this be fixed without reloading the page? I climbed into the docks, scrolled down to X-CSRFToken, but did not understand how to steer them.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexNest, 2021-06-15
@AlexNest

If I understand the problem correctly, then something like this, if used directly in the template.

function add_to_cart(id) {
        let token = '{{csrf_token}}';
        $.ajax({
            headers: { "X-CSRFToken": token },
            url: '/add-to-cart/',
            type: 'POST',
            data: {'id':id},
            success: function(data) {

                get_cart()
                
            },
            failure: function(data) {
                console.log('Не успешно');
            }
        });

    }

In theory, I see no problem in specifying token / {{csrf_token}} when calling a function. Then it can be taken out in a separate file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question