CSRF token not being set in Django leading to 403 on client-side

33 Views Asked by At

When making a POST request with axios from an endpoint in django, the CSRF token cookie seems to not be set, because of this it gives me a 403 status code. which i couldn't fix even after days trying to

BACKEND: i've used cors-headers in django to set up in settings the CSRF_TRUSTED_ORIGINS,CSRF_COOKIE_DOMAIN and the CORS_ALLOWED_ORIGINS to all match the origin frontend's url but still didn't work. i also set CORS_ALLOW_CREDENTIALS = True, for context

the middlewares config are on point too though. in the endpoint view i have already tried ensure_csrf_cookie with no success, because it is a class-based-view i have tried method_decorator too without success

FRONTEND: i have defined default names for csrf header and token name in order for me to include them in my axios.post call and get the actual value of the csrftoken cookie with a getCookie function but it always returns null, which probably means the server-side isn't setting this csrf cookie at all :( :

axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken';)

the function is the getCookie(code at the end) that takes the defined name of the cookie as a param: const csrftoken = getCookie('csrftoken')

for that to be later included into my axios call:

    const response = await axios.post(
        'http://localhost:8000/api/register',
        { username, password },
        {
        withCredentials: true,
        headers: {
        'X-CSRFTOKEN': csrftoken
        }
    }

getCookie func:

    function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + '=') {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
            }}}

    if (cookieValue == null){
            console.log('cookie null')}

    return cookieValue;
    }
0

There are 0 best solutions below