Set-Cookie响应头不能使用Angular 2 + django-rest-framework [英] Set-Cookie response header not working using Angular 2 + django-rest-framework
问题描述
我正在开发一个使用django-rest-framework后台的Angular 2应用程序。我正在使用开发服务器(ng从角 - cli)进行测试,另一个用于django(默认来自manage.py)。这两个服务器都可以从127.0.0.1访问,但在不同的端口可用。
I am developing an Angular 2 app that is using django-rest-framework a backend. I am doing my tests using a development server (ng serve from angular-cli) and another one for django (default from manage.py). Both server are accessible from 127.0.0.1 but on different ports.
我的身份验证系统基于django-rest-framework提供的cookie。当使用django-rest-framework中的视图时,一切都可以正常工作。
My authentication system is based on cookie served by django-rest-framework. Everything works fine when using the views from django-rest-framework.
当我尝试从角度2登录时,我收到一个带有Set-Cookie头的有效响应。问题是cookie不会在浏览器中设置(在chrome和firefox中测试)。
When I try to login from angular 2, I receive a valid response with a Set-Cookie Header. The problem is that the cookie is never set in the browser (tested in chrome and firefox).
这是CORS问题吗?我的corsheader应用程序安装了以下参数
Is this a CORS problem? I have corsheader app installed with the following parameters
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
推荐答案
据了解,django-cors(一般基本上都是cors)允许所有和同时允许凭据,这是从cors中间件:
As I understand the django-cors (and basically cors in general) you can not set allow all and allow credentials at the same time, this is from cors middleware:
if conf.CORS_ORIGIN_ALLOW_ALL and not conf.CORS_ALLOW_CREDENTIALS:
response[ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
else:
response[ACCESS_CONTROL_ALLOW_ORIGIN] = origin
patch_vary_headers(response, ['Origin'])
所以基本上你需要有原点正确设置 - 因为你与两个Trues去到其他块;
So basically you need to have origin properly set - as you with both Trues goes to the else block;
您可以在这里阅读更多信息: MDN CORS ,特别是这个片段:
You can read more about it, here: MDN CORS, especially this fragment:
重要提示:响应一个凭证请求,服务器必须指定一个域,并且不能使用通配符。如果标题为通配符,则上述示例将失败:Access-Control-Allow-Origin:*。由于Access-Control-Allow-Origin显式提及 http://foo.example ,将凭据认证内容返回给调用的Web内容。请注意,在第22行中,进一步的cookie被设置,如果发生故障,根据使用的API会产生异常。
"Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *. Since the Access-Control-Allow-Origin explicitly mentions http://foo.example, the credential-cognizant content is returned to the invoking web content. Note that in line 22, a further cookie is set. In case of failure, an exception, depending on the API used, is raised."
这篇关于Set-Cookie响应头不能使用Angular 2 + django-rest-framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!