cookie disappeared in AngularJS app using Django a

2019-06-03 16:11发布

问题:

I'm building an AngularJS app with Django Rest Framework and Django CORS Headers as backend API.

Everything was working fine until today. Suddenly the csrfcookie and sessionid cookie stopped showing up in Chrome.

I see the API responding to me with the csrfcookie. Chrome doesn't show it in dev tools, however I see it in chrome://settings/cookies.

AngularJS

$httpProvider.defaults.useXDomain = true;
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$http({withCredentials: true, ...})

Django API

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = (
    'x-requested-with',
    'content-type',
    'accept',
    'origin',
    'authorization',
    'X-CSRFToken'
)

回答1:

Ok so the answer to this issue is quite simple but not always very easy to notice since there are no error messages from the API, nor the client.

The problem above is that I reside on domain.com in my browser, but my request is towards the API is to "www.domain.com:8000". Both www.domain.com and domain.com are allowed origins in my API.

Conclusion here is that if I reside on domain.com then I need to make my API request towards domain.com:8000. But if reside on www.domain.com in my browser, then I need to make my API request towards www.domain.com:8000.

Se a working example down bellow:

Cookies now appear fine!

I hope this helps anyone, saving a few hours of frustration :)

Update: Enabling the following settings in the Django settings file will also solve the problem. Using them let's you reside on different subdomains in your browser, and the cookies will return for domain ".domain.com"

https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-domain https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-domain

Thanks to apollo on irc.freenode.net, #django for the updated answer.