Making An App With PhoneGap & jQm Part III: A Stateless Authentication Layer 33

If you missed Part II: Loading JavaScript Properly, you may want to go there and grab the code we wrote so far so that you can follow more easily what we'll do in this part.

Today, we'll see how to implement a RESTful, stateless authentication layer in our application. Let's first talk a bit about REST; the acronym stands for "REpresentational State Transfer" and describes a way of handling client-server transactions in a uniform, layered, stateless, scalable and cacheable way. I know that's a lot of adjectives to process so I won't delve into much more details here. We'll focus on the stateless constraint, which requires that the exchanges have no memory per se, they always contain all the information that the other party has to know to process them correctly.

I have tried to simplify my code examples as much as possible. The goal being "stateless authentication", I have focused on that, which means that for now we will deal with "ugly" URLs like https://foo.bar/server.php?a=b&id=123; we'll see in a while how to do the same with "clean" URLs like https://foo.bar/users/bob

The REST philosophy is widely considered one of the best ways to solve communication challenges between a client and a server over the Internet. You may want to read the linked Wikipedia article for more details about the how and why.

Now what we're interested in is the design of a system in which we can "phone home" from our application to an online server. This is needed for applications which have to pull data from a remote host like news items or score boards, or on the contrary push data to a remote host like creating a new account or updating profile information. Obviously such a system must allow for authentication, or we could end up with users accessing or modifying other users' data at will!

Phoning Home (Cross-Domain) With jQuery

Phoning home is surprisingly easy with PhoneGap & jQuery, and at the same time it can prove hard to do it right. What I mean is that on the one hand jQuery provides us with powerful tools like jQuery.ajax(), which we can leverage in order to query our servers; on the other hand, there is a bunch of things we need to do so that our query is not blocked by the anti-cross-domain security features embedded in web browsers like Chrome.