First off, you don't need to worry about cross-domain restrictions in a PhoneGap app.
Remember that it's the browser that enforces same-origin rules. The only involvement your server might have is when a page on a different domain tries to make a XHR request for something on your server; the CORS specification outlines how that's handled. If you respond with appropriate Access-Control-Allow-Origin
headers, the XHR request is allowed unrestricted.
So in PhoneGap, there is no browser enforcing same-origin rules – only PhoneGap's configuration (which you control). PhoneGap allows you to specify which domains (or all) your app will have access to. Once whitelisted, your code will be able to make XHR requests to those domains with no restrictions.
The only sticky thing is that when using jQuery to make XHR requests, it will try to convert your requests into JSONP, incorrectly assuming that it must work around same-origin rules.
To fix this, you can force jQuery to always use XHR:
$.ajaxSetup({crossDomain:false});
Regarding Authorization
, that's fairly simple. A client sends the string literal Basic
, a space, and then the username, a colon, and the password base64-encoded.
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Decoding the base64 data yields Aladdin:open sesame
.
Based on the jQuery snippet you added, your HTTP request looks like this:
POST /form.php HTTP/1.1
Host: example.com
X-Requested-With: XmlHttpRequest
Authorization: TRUEREST
username: dave
password: test
apiKey: qwe123
...
It should be obvious why $_SERVER['HTTP_AUTHORIZATION']
only contains TRUEREST
: the other items are completely separate (and invalid) headers. Try:
headers: {
Authorization: 'X-My-API ' + $.param({
username: 'dave',
password: 'test',
apiKey: 'qwe123'
})
}
Now your request will look like this:
POST /form.php HTTP/1.1
Host: example.com
X-Requested-With: XmlHttpRequest
Authorization: X-My-API username=dave&password=test&apiKey=qwe123
...
$.param
serializes an object into a URL-encoded query string.- You should probably consider base64 encoding the authorization data, just like HTTP Basic auth. This will ensure that only [A-Za-z0-9+/=] (printable) characters are in the HTTP headers, potentially avoiding security problems.
- I'm not entirely clear on the RFC's requirements, but by convention, non-standard extensions to HTTP are usually prefixed with X-. Since your authorization scheme is non-standard, you should do the same.
- The
OPTIONS
request you are seeing is CORS at work. If you specify custom headers in a cross-domain XHR request, the browser first checks with the server to see if it sendsAccess-Control-Allow-Origin
headers in response (the "preflight request"). Only if it does will the browser send the actualPOST
with data.