11
votes

I'm developing a PhoneGap application that communicates with a secure .net server. The issue is, I can't seem to pass along any Cookies with any request (W3C).

This is what I am doing (assume that "username" and "password" work).

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;
    });

At this point I have an authentication token that I can use to validate all subsequent requests. So using that token I make another request to the server...

$.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 just says: Refused to set unsafe header "Cookie" (which adheres to the W3C spec). The app doesn't set the header and as a result the request 401s because the authorization cookie is not sent.

My question is this: Is there any way to subvert this and override the Cookie header (or another way to go about it entirely) on PhoneGap? I know that using an Authorization header is also an option, but I have limited access to the server (which doesn't support it) and was hoping for a more immediate solution.

Bonus question: The call to the AuthService should also set an httpOnly cookie on the device, but does not (I speculate that this is because it is cross domain request)... Am I correct in this assumption, or could there be something wrong server side?

Thanks!

1

1 Answers

6
votes

The short answer is no, you can't set the Cookie header. The reason for this is that Chrome is your User Agent, so it is required by the HTTP specification to disallow modifications to headers which have security implications.

One solution would be to perform an action that allows the server to set the cookie on your XmlHttpRequest object. You say you're already trying to do this but it's not working. I suspect that's because you need to set withCredentials on your ajax request. Add the xhrFields attribute, as follows.

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;
});

Now as long as the responding server doesn't send a wildcard as its CORS allowed domains (Access-Control-Allow-Origin), you should receive the cookie.