[Vuejs]-How to use csrf token in Django integrated with vuejs using Django webpack loader?

0👍

I find the answer , I searched a lot but I couldn’t find a place with proper description of using csrf in Django rest framework integrated with single page applications like react and vuejs, so I first answer my question and then write down the whole configuration.
the answer for first part of my question is that you should use @csrf_protect decorator instead of @requires_csrf_token because even though @requires_csrf_token works similarly to csrf_protect, but never rejects an incoming request.
although I fixed this but my request were processing without any csrf token, there was another problem and it was as DRF documentation stated, "CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied", so anonymous request does not require csrf token, all I had to do was place @api_view decorator above @csrf_protect to authenticate user first and it solve this problem.

@api_view(['POST'])
@csrf_protect
@c_login_required()
def create_from_csv(request):
    if 'data_' in request.data:
        return JsonResponse({})
    else:
        raise MyValidationError({
                'message': 'اطلاعات ورودی درست نیست!!'
            })

for the second part of my question you just had to retrieve token as above and then send the token in request header "X-CSRFToken": yourcsrftoken

in summary:
1- use @ensure_csrf_cookie on the view that renders the page which request comes from, This decorator forces a view to send the csrf cookie.
2- retrieve the token as above and send the token along post request in request header with the this key: X-CSRFToken.
3- use @csrf_protect on the view that handles the post request after authenticating user because in Django rest frame work anonymous users doesn’t require a token

Leave a comment