PhoneGap中的Cookie标头:拒绝设置不安全的标题" Cookie"

时间:2013-07-25 01:03:29

标签: javascript jquery cordova

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

这就是我正在做的事情(假设“用户名”和“密码”有效)。

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规范)。该应用程序未设置标头,因此请求401s,因为未发送授权cookie。

我的问题是:有没有办法颠覆这个并覆盖PhoneGap上的Cookie标题(或其他完全解决方法)?我知道使用Authorization标头也是一种选择,但我对服务器的访问权限有限(不支持它),并且希望能够提供更直接的解决方案。

奖金问题:对AuthService的调用还应该在设备上设置一个httpOnly cookie,但不会(我推测这是因为它是跨域请求)...我在这个假设中是正确的,还是可以在那里是服务器方面的错误吗?

谢谢!

1 个答案:

答案 0 :(得分:5)

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

一种解决方案是执行允许服务器在XmlHttpRequest对象上设置cookie的操作。你说你已经在尝试这样做,但它没有用。我怀疑那是因为你需要在你的ajax请求上设置withCredentials。添加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。