Here is my class, extending from from django.views.generic import View
:
class ClassView(ProtectedView, View):
def __init__(self):
self.client = get_default_client()
def get(self, request, item_remove, item_replacement):
... code ...
return JsonResponse(data)
def post(self, request, item_remove, item_replacement):
... code ...
return JsonResponse({})
ProtectedView
mixin:
@method_decorator(login_required, name='dispatch')
@method_decorator(superuser_required, name='dispatch')
class ProtectedView(object):
def dispatch(self, *args, **kwargs):
return super(ProtectedView, self).dispatch(*args, **kwargs)
Ajax call :
this.utils._ajax({
method: 'post',
url: `/api/shortage/${this.item_remove}/${this.item_replacement}`,
data: {
item_type: 'product_bundle',
delivery: productBundles,
}
})
Ajax object :
_ajax(req) {
const csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
this.$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
const ajax$ = this.$.ajax({
url: req.url,
dataType: 'json',
method: req.method,
data: req.data,
xhrFields: {
withCredentials: true
},
});
return ajax$;
}
Headers in request
{
'Content-Length':'50',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Host':'localhost:8000',
'Connection':'keep-alive',
'Accept':'application/json, text/javascript, */*; q=0.01',
'Origin':'http://localhost:8000',
'X-Csrftoken':'QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9',
'X-Requested-With':'XMLHttpRequest',
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Mobile Safari/537.36',
'Sec-Fetch-Site':'same-origin',
'Sec-Fetch-Mode':'cors',
'Referer':'http://localhost:8000/admin/shortage',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'en-US,en;q=0.9',
'Cookie':'csrftoken=QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9; pnctest=1; logglytrackingsession=37c9453d-1b2c-443d-9a8e-167c8576cb8b; sessionId=68a017ab-a1d5-43a3-93c3-4df44b3851c3; sessionid=zl2k7hwechu0uprq4tqw66znc91op5ua'
}
CSRF Token is clearly contained in headers, but still, the method always return (403) CSRF verification failed
Any idea to fix this issue? Thanks.
Edit: Since this part is still in development, I added @method_decorator(csrf_exempt, name='dispatch')
to my class to keep going. Obviously I don't recommend this as a solution.
Set CSRF_USE_SESSIONS
and CSRF_COOKIE_HTTPONLY
to False.
Read more at https://docs.djangoproject.com/en/2.2/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false