jQuery Ajax and REST HTTP Basic Authentication: done deal!
“I’m talking done deal, closed case
Ain’t no time for looking back on the road you take
You gotta claim your spot, nobody hold your place
Ain’t no time to preach about time you chose to waste
You gotta mold your fate, hold your weight” Done Deal - Lil’ Wayne
As previously mentioned, while we did hit a road bump during our REST authentication implementation, we are now comfortable with the following solution. A live demo should be available soon.
On the client-side, the basic idea (directly inspired by Aswin Anand’s solution) is to craft the Authorization request header in a beforeSend callback instead of relying on jQuery’s own username/password mechanism. Using such seems to circumvent the browser login dialog. As per RFC 1945, the Authorization header value should contain the username:password as encoded (base64) string, which would result in something like the following header:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
On the server side, on top of the AuthBasic module, we rely on a neat nginx trick (which I’m sure is also available on Apache). Indeed, upon access denied, without this minor tweak, the server would return a 401 HTTP status code (Unauthorized) along with a WWW-Authenticate header. While this corresponds to the expected behavior as part of the RFC, this combination triggers the browser login popup dialog, which does not really blend in terms of UX.
In order to circumvent this aspect, instead of returning a 401, a 403 (Forbidden) status code is used, which seems fair enough from our perspective. Hence, we ended crafting the following nginx configuration:
We still have to figure out some details like the following:
- Session Timeout
- Username Password Cookie Persistence
- Direct Resource Access Redirect
Another upcoming blog post should cover those aspects.
Stay tuned or follow me on twitter here.
UPDATE: it appears that this blog entry is one of the most popular among my blog visitors, and I'm really glad for it if this post could be of any help. That being said, I'd like to hear from you! Whether it helped or not, leave a comment and your thoughts about this solution. Or ping me on twitter.