Hi,
Not sure if this breaks any RFC’s or there’s another valid reason why this doesn’t exist already but I’ve noticed that certain client frameworks (looking at you angular) have a tendency to put POST data in the request body.
For example, the following angular code
$http( {
method: 'POST’,
url: theurl
headers : {
'Content-Type': 'application/json; charset=utf-8'
},
data: { 'csrfmiddlewaretoken': thetoken),
‘foo’ : bar}
};).
The csrfmiddlewaretoken then ends up in the request.body as a json string (regardless of the content-type) and not request.POST and the csrf middleware rejects the request. I’m not an angular expert but as far as I can tell if the data is not a simple string then it gets JSON’fied and ends up in the request body.
I was proposing adding the following to csry.py as a last chance saloon attempt to find the token
# Last chance, check the body for a JSON payload
if request_csrf_token == "":
try:
bodydict = json.loads(request.body)
request_csrf_token = bodydict.get('csrfmiddlewaretoken', '')
except:
pass
I’ve created a fork and branch with this modification
https://github.com/rjjeffries/django.git - branch csrf_jsonbody
Thanks
Richard