0

I'm using Django Rest Framework. In my login_view I created a csrf token and set it as cookie. I examined the login response and I can see it is properly set as Set-Header token. Let me summarize my problems:

1-) For a subsequent user request I couldn't set the cookie as axios header since document.cookie is resulting empty in the Vue side. As a result, Im getting error as the rest framework pushes for csrf validation and csrf middleware fails to compare cookie with the request header.

2- I'm not sure if the problem related to that I'm testing this on my localhost.

3-) I'm not sure if I carry the csrf framework correctly.

The following is summary of my code

from django.middleware.csrf import get_token

class user_login(APIView):
    def post(self, request):
        response = Response()
...

        csrf_token = get_token(request)
        response.set_cookie(
                key='csrftoken',
                value=csrf_token,
                httponly=False,
                secure=False,
                samesite='None',
            )
...
        return response

In the Vue side:

axios.defaults.headers.common['X-CSRFToken'] = getCookie('csrftoken');

axios
        .post(
            user_request,
            {
                user_data: user_data,
            },
            {
                withCredentials: true
            }

And the getCookie function is implemented as depicted in Django documentation:

const getCookie = function(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();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

No matter what I tried the document.cookie is empty.

0