CSRF Cookie not set when posting request with AngularJs - Django Backend

痴心易碎 提交于 2020-01-11 09:58:07

问题


I'm building a web app with angularjs and django and I'm submitting form via Ajax request.

My problem is that when posting an Ajxa request with angular (ng-file-upload precisely) the csrfmiddlewaretoken expected by django is not set.

From my lectures on angular documentation and other forums I ended up with the following configuration.

In the config part of angular :

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentials = true;

and in my controller the code for sending the request is :

Upload.upload({
                url: 'http://localhost:8000/image',
                headers: {
                  'X-CSRFToken': $cookies['csrftoken']
                },
                data: {file: file}
            })

With that code the request send has the following headers :

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2,fi;q=0.2
Connection:keep-alive
Content-Length:16582
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarybWo821vSwcejTATP
Cookie:csrftoken=bC2UpXurGXAg3AUZgSqMVlUs8TKfussS
Host:localhost:8000
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
X-CSRFToken:UeSt4LoqgU9L28JQBdVbS2IJJXOMQK6n

However for django to be able to handle csrf protection correctly the following header is missing

Cookie:_ga=GA1.1.1358238168.1447425523; XSRF-TOKEN=zWIM6q7O2Nz3PLm8TMUJSLFVRF8bKUbr; csrftoken=UeSt4LoqgU9L28JQBdVbS2IJJXOMQK6n

So far and despite having seen a lot of forums about this topic I didn't manage to set this header. if I try to set it programmatically via :

Upload.upload({
                url: 'http://localhost:8000/image',
                headers: {
                  'Cookie': 'csrftoken='+$cookies['csrftoken']
                },
                data: {file: file}
            })

I end up with the following error in my console :

Refused to set unsafe header "Cookie"

My problem is really how to configure the cookie header from the client side. My django code is fine.

I have been struggling with this for quite a time now. Any help would be appreciated ! Thanks


回答1:


If you added in the csrftoken to client headers: {'X-CSRFToken': $cookies['csrftoken']} means your client is most probably ready, but for security matter if you interact with django api from external application he will still block the request returning unsafe header "Cookie". try the following configuration to allow the cross site request over your app:

pip install django-cors-headers

and then add it to your installed apps in your settings.py:

INSTALLED_APPS = (
...
'corsheaders',
...
)

You will also need to add a middleware class to listen in on responses and make sure you respect the order as follow:

MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)

and finally add this settings variable:

CORS_ORIGIN_ALLOW_ALL = True

This should be enough but for more customized configuration you can check django-cors-headers



来源:https://stackoverflow.com/questions/34206779/csrf-cookie-not-set-when-posting-request-with-angularjs-django-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!