Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

204 | Chapter 7: REST, Resources, and Web Services


The precedingupdatemethod illustrates a difference between REST in
theory and RESTful Rails in practice. In Rails, thePUTmethod is
always mapped toupdate, while REST in general can also usePUTto
create resources. We work around this by allowing creation from the
update method, to allow us to use the more RESTful design.
Traditionally, Rails would usecreatefor this action, which would
requirePOSTing “product_id=123” to the parent resource at/carts/4/
products. This would be a RESTful design if the server chose the
resulting URI (for example, if theLineItem’s ID was used instead of a
combination of cart and product ID). However, because the client has
all of the information about the resource’s URI (/carts/4/products/
123 ), it should justPUT the resource to that URI.

At first glance, this code may seem to be much more complicated than the original,
non-RESTful code. However, we have moved a great deal of functionality out of the
framework (removing the dependency on sessions) and made the session state into
an explicit set of resources. One of the big advantages that we gain is that the state
now has all of the benefits of REST; state items are addressable, and we can now use
a stateless server, assisting in scalability. This RESTful architecture is much more
uniform than the old architecture, because it uses standard HTT Pand CRUD meth-
ods instead of custom ones.


Authentication


Many web services and web applications need authentication of their users. Unfortu-
nately, RESTful authentication on the human-readable Web is in a sad state.
RESTful HTT Pweb services designed to be consumed by machines tend to have
more options, because the developer of the application can somewhat dictate how
the client must connect, even if it involves custom authentication schemes.


For browser-based web sites and web applications, there are fewer options; for an
application to be usable by humans on the public Web today, it needs to support the
browsers its clients will be using.


There are two methods commonly supported in browsers for HTT Pauthentication:
Basic and Digest. Both are defined and explored in RFC 2617 (http://tools.ietf.org/
html/rfc2617). Basic authentication is very simple, but it is insecure. Usernames and
passwords are sent in plain text over the network.*Digest authentication is a step up;
it uses a challenge/response mechanism for the client to prove it knows the pass-
word without sending it over the network.


Digest authentication could technically violate the statelessness principles of REST.
The nonce values that the server generates during the authentication process must be



  • The easiest solution, as with forms-based authentication, is to encrypt the entire login transaction with SSL.

Free download pdf