I have a strange issue with CSRF in Django. Here are the relevant portions:
In my javascript file I have:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// 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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(function () {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
})
$.post('/api/jpush',
$.param({'recipients': recipients, 'message': message, 'url': url,
'url_title': url_title, 'priority': priority,
'csrftoken': getCookie('csrftoken')}),
...
then I have in my view:
def push(request):
return render(request, 'api/push.html')
def jpush(request):
tmplData = {'result': False}
if not request.POST:
return HttpResponseBadRequest(request)
elif request.POST.viewkeys() & {'recipients', 'message', 'priority'}:
tmplData = { 'results': send(request.POST) }
return JsonResponse(tmplData)
....
and in my template:
<form id="push" class="form-horizontal" action="" method="post">{% csrf_token %}
However when I post using ajax I get a 403 and firebug shows me that the crsftoken value is null and the csrftoken cookie is httpOnly. I have set CSRF_COOKIE_HTTPONLY
to False in my settings.py
so I don't understand why the cookie is being forced as httpOnly. I am using Django 1.10.
Thanks