PhoneGap中的Cookie标头:拒绝设置不安全的标头“;Cookie”;

Cookie Header in PhoneGap: Refused to set unsafe header "Cookie"

本文关键字:Cookie 设置 标头 中的 拒绝 PhoneGap 不安全      更新时间:2023-09-26

我正在开发一个PhoneGap应用程序,它可以与安全的.net服务器通信。问题是,我似乎不能随任何请求传递任何Cookie(W3C)。

这就是我正在做的(假设"用户名"answers"密码"有效)。

var token;    
$.ajax({
        url: "https://server.com/AuthService/api/account/login",
        crossDomain: true,
        type: 'post',
        async: false,
        data: {
            username: "username",
            password: "password"
        }
    }).done(function(response) {
        token = response.securityToken;
        success = true;
    });

此时,我有一个身份验证令牌,可以用来验证所有后续请求。因此,我使用该令牌向服务器发出另一个请求。。。

$.ajax({
    url: "https://server.com/Service/api/search?query=" + query,
    headers: { Cookie: 'auth=' + token },
    crossDomain: true,
    withCredentials: true,
    type: 'POST',
    async: false,
    data: ' ' //because we don't want our request to be 0 bytes (the server is picky)
}).done(function(data) {
    result = data;
});

Chrome只是说:拒绝设置不安全的头"Cookie"(符合W3C规范)。该应用程序没有设置头部,因此请求401,因为没有发送授权cookie。

我的问题是:有没有任何方法可以颠覆这一点,并在PhoneGap上覆盖Cookie标头(或另一种完全实现它的方法)?我知道使用Authorization头也是一种选择,但我对服务器的访问权限有限(不支持它),希望能有一个更直接的解决方案。

额外的问题:对AuthService的调用也应该在设备上设置httpOnly cookie,但没有(我推测这是因为它是跨域请求)。。。我的这个假设是正确的吗,或者服务器端可能出了什么问题?

谢谢!

简短的回答是否定的,您不能设置Cookie标头。原因是Chrome是您的用户代理,因此HTTP规范要求它不允许对具有安全隐患的标头进行修改。

一种解决方案是执行一个操作,允许服务器在XmlHttpRequest对象上设置cookie。你说你已经在尝试这样做了,但没有效果。我怀疑这是因为您需要在ajax请求上设置凭据。添加xhrFields属性,如下所示。

var token;    
$.ajax({
    url: "https://server.com/AuthService/api/account/login",
    crossDomain: true,
    xhrFields: {withCredentials: true},
    type: 'post',
    async: false,
    data: {
        username: "username",
        password: "password"
    }
}).done(function(response) {
    token = response.securityToken;
    success = true;
});

现在,只要响应服务器不发送通配符作为其CORS允许的域(Access Control Allow Origin),您就应该收到cookie。