Bear with me, this one needs a bit of explanation.
I am helping to build a hybrid mobile web app. The main codebase is HTML5 and JavaScript, which will be wrapped in a native mobile Web View (a la Phonegap).
Part of the functionality requires the app to post information to a web service controlled by one of our clients. There is very little scope to change this web service as it is being used by others. We send JSON using an HTTP POST and receive responses from the server. Part of this response is a JSESSIONID cookie which manages our session with the server. After the initial initSession()
call, we need to send the JSESSIONID cookie with every (AJAX) request.
When deployed on a mobile device, the web app is wrapped in the native Web View, which starts the web app by browsing to file:///path/to/app/index.html
.
The first thing we tried was asking our client to set Access-Control-Allow-Origin: *
in their response header to allow CORS. We then tried posting to the server:
$.ajax({
url: 'http://thirdparty.com/ws',
data: data,
type: "POST",
dataType: "JSON",
success: successCallback,
error: failedCallback
});
Monitoring the requests, it was apparent that the cookies were not being included. On closer inspection there is a special section in the CORS spec for dealing with user credentials, which includes session cookies. So I modified the AJAX call to include this:
$.ajax({
url: 'http://thirdparty.com/ws',
data: data,
type: "POST",
dataType: "JSON",
success: successCallback,
error: failedCallback,
xhrFields { withCredentials: true }
});
Another error, this time from the Browser. More reading yielded the following:
If the third party server did not respond with an Access-Control-Allow-Credentials: true
header the response would be ignored and not made available to web content.
Important note: when responding to a credentialed request, the server must specify a domain in the Access-Control-Allow-Origin
header, and cannot use wild carding.
So we need to change the server's headers to include Access-Control-Allow-Credentials: true
and Access-Control-Allow-Origin
to our Origin.
Here we finally come to my problem: when loading a web page using the file:// protocol, the Origin
request header sent from the Web View is set to null
. It therefore can't be parsed by the server and so the server can't set it in Access-Control-Allow-Origin
. But if the server can't set Access-Control-Allow-Origin
to something other than *
we can't send credentials, including cookies.
So I'm stuck. What to do? I saw a similar question posted here but I don't really understand the proposed answer. Any help would be much appreciated!
See Question&Answers more detail:
os