CSRF token missing or incorrect. Django + AngularJS

泄露秘密 提交于 2019-12-05 08:33:48

As @Chris Hawkes pointed to this stackoverflow answer given by @Ye Liu

Since the angular app isn't served by django, in order to let the cookie to be set, angular app needs to do a GET request to django first.

I verified that as long as you don't make http get request, csrftoken cookie doesn't get set. So only

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

would not work. You first need to make if not real then mock http get request to django rest_framework.

Update: Your comments pushed me to further study it, Please read this blog where is has mentioned as,

CLIENT-SIDE GENERATED CSRF-TOKENS. Have the clients generate and send the same unique secret value in both a Cookie and a custom HTTP header. Considering a website is only allowed to read/write a Cookie for its own domain, only the real site can send the same value in both headers

So lets try with this single request first.

$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

where you are injecting $cookies to the controller/service.

If it works then may be writing interceptors would be good choice, and would help you to debug as well.

I am sure you are using AngularJs version at least 1.2, See this changeset and in recent commit Angular http service checking csrf with this code,

var xsrfValue = urlIsSameOrigin(config.url)
            ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
            : undefined;
        if (xsrfValue) {
          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
        }

So it's necessary that you are sending same token which is present in cookie.

Further to analyse use developer tool of your browser to see request/response with the http request and analyse headers and cookies.

if you are using $http in AngularJS for ajax request and if you are facing any CSRF token issue then use this:

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