Web Services and Goldberg

One of the hottest topics in the Rails community at present is the use of REST and respond_to to provide web services. Goldberg supports the use of respond_to for its goldberg/auth/login action to authenticate XML requests. Instead of a rendered page, the client receives a meaningful HTTP status code. As a result, all the security features Goldberg offers are available for web services interaction.

In summary the procedure would be for the client application to POST login credentials and check the status code it receives. If the request was successful then the client is effectively logged in, and can continue a conversation with your site's other controllers that provide XML services. The client simply has to keep sending back the same cookie it was given on login. The following client application — although trivial — is a fully functional demonstration of the techniques involved.


require 'net/http'

# Start the connection
Net::HTTP.new('localhost', 3000).start do |http|
# Formulate new POST request and set appropriate headers
login = Net::HTTP::Post.new('/goldberg/auth/login')
login.set_form_data({ 'login[name]' => 'admin',
'login[password]' => 'admin' })
# Tell the server we want to talk XML
login.add_field 'Accept', 'application/xml'

# Send the login POST
response = http.request(login)

case response
when Net::HTTPSuccess # Login accepted
# Get the cookie
cookie = response.header['set-cookie']

# Do other stuff here, for example:
response = http.get('/goldberg/users/list', {'Cookie' => cookie})
puts response.body

else # Login rejected
# Throw exception
response.error!
end
end

Further Reading


Login