#Forbidden (CSRF token missing) with Ajax Validation

15 messages · Page 1 of 1 (latest)

fast drum
#

I'm trying to do a form validation with Ajax, but getting a CSRF error. I'll supply some code snippets of relevence, any guidance or explanations would be super appreciated ❤️ thanks in adance!

settings.py:
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:8000/app/','http://127.0.0.1:8000/' ]
app.js:
$("#username").change(function () {
    var username = $(this).val();
    $.ajaxSetup({
        header: {
            "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value 
        }
    });
    $.ajax({
        url: 'validate',
        method: 'POST',
        data: {
            'username': username 
        },
        dataType: 'json',
        success: function (data) {
            if (data.taken) {
                alert("Username already in use!");
            }
        }
    });
});
register.html:
{% extends 'base.html' %}

{% block content %}
<div class="col-lg-4 container dark">
    <div class="app">
        <h2>Sign Up</h2><br>
        <form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="text" class="form-control mb-3" id="username" placeholder="Username">
            <input type="password" class="form-control mb-3" placeholder="Password">
            <input type="password" class="form-control mb-3" placeholder="Repeat Password">
            <input type="button" value="Submit" class="btn">
        </form>
    </div>
</div>

{% endblock %}
#

Error reads: Forbidden (CSRF token missing.): /app/validate
[10/Mar/2024 15:35:19] "POST /app/validate HTTP/1.1" 403 2505

shrewd hull
#

You need CSRF token in 2 places

#

e.g. send it with form data as well

fast drum
#

can you elaborate a little further?

#

i have the token in the html form, and i also have it inside the ajax call.

shrewd hull
#

In ajax I only see it being set to header

#

It's correct but it's not enough

fast drum
#

literally everything i read says that you just need it in the header of your ajax call D:

#

i can't find any documentation stating otherwise.

shrewd hull
#

Well, from django docs:

For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.

#

Though it talks about cookie, but I believe header can substitute the cookie

#

But point you need two

fast drum
#

in django docs, here is their example of calling a ajax call properly:

const request = new Request(
    /* URL */,
    {headers: {'X-CSRFToken': csrftoken}}
);
fetch(request, {
    method: 'POST',
    mode: 'same-origin'  // Do not send CSRF token to another domain.
}).then(function(response) {
    // ...
});
#

in classic django fashion, i changed nothing and restarted the server 3 times and it works now.