At the Forge

Integrating OpenID

Reuven M. Lerner

Issue #171, July 2008

Integrate OpenID into any Rails application, using off-the-shelf libraries and a bit of custom code.

The past few months, we've looked at two different ways to authenticate users coming to a Web site. First, we looked at OpenID, an increasingly popular distributed authentication system. With OpenID, users control their information, as well as which applications are allowed to use that information.

Last month, we looked at acts_as_authenticated, a plugin for the Ruby on Rails framework that is quite traditional, asking visitors to enter a user name and password in order to access restricted services.

This month, we take an initial look at how we might be able to incorporate OpenID—and by extension, a combination of OpenID and traditional authentication—into our own Rails applications. In OpenID lingo, we want our application to be a “consumer”, asking an OpenID “provider” of the user's choosing for authentication information, rather than gathering and checking that information ourselves.

OpenID is a pretty well established standard, and integration into a Rails application isn't all that difficult. However, the number of OpenID-supporting libraries and plugins has gotten a bit out of control, such that it's sometimes hard to know (or believe) which ones actually work, not to mention which ones are easiest to work with.

Authentication and OpenID

Authenticating users for a Web site is normally a straightforward task. You ask users, via an HTML form, to enter their user names and passwords, and then compare that combination against the database. (For security purposes, of course, it's usually best to encrypt the password in the database, and then compare the encrypted input with what is in the database.) If the user name/password combination exists in the database, the user can log in.

Of course, HTTP is a stateless protocol, which means there isn't really any such thing as being “logged in”. Rather, we rely on cookies, pieces of data provided by the server but stored in the user's browser, which are passed to the server with each subsequent HTTP request. In this system, logging in takes place when the server sets a cookie on the user's browser. In Rails and many other Web frameworks, cookies also are used to keep track of a user's “session”, attributes associated with this user on this browser.

In order to incorporate OpenID into a Web application, we don't need to replace the whole cookie/session/login portion of the framework. Rather, we need to change the way we authenticate users, setting the login cookie after an OpenID provider has indicated that a user has been identified legitimately.

A traditional Rails-based login system would involve an HTML form, a controller action that compares the submitted form values against a database, and then a login page. To replace this with OpenID, we need to modify our controller such that it asks an OpenID server to authenticate the user.

But, wait a second. The whole point of OpenID is that users enter a URL (that is, their unique OpenID), and that they authenticate against a server associated with that URL. This means the HTML form needs to change, such that it asks for a URL instead of a user name and password.

Moreover, we have to take into account the fact that our server needs to redirect users to an OpenID server, which then will redirect back to our system, indicating whether the user has logged in successfully.

There are, as I indicated above, many Ruby- and Rails-related resources having to do with OpenID. Unfortunately, many of them are poorly documented, out of date or relatively hard to use. For example, there is a Ruby gem called openid_login and a plugin called open_id_authentication that might well work with a bit of hacking. But, their documentation is out of date, and I encountered problems with, among other things, the double suffixes (.html.erb) that Rails now uses with templates. So, although I'm sure it's possible to get this gem to work with OpenID and modern Rails installations, it probably will take time and effort—more than I would expect from a prepackaged solution.

Thus, my suggested solution to the whole question of OpenID is to use the simple, low-level ruby-openid gem, which happens to have support for Rails applications built in. This gem is actually very well documented in its current form—version 2.0.4 at the time of this writing. But, be careful; much of the documentation you'll find on-line is out of date and implements OpenID-related functionality using the 1.x version of this gem with an older, incompatible API.

To install the gem, of course, we write:

gem install ruby-openid

We then create a controller for handling our OpenID-related actions:

script/generate controller openid new create complete openid_consumer

These four actions, the fourth of which is private, are what we'll need in order for people to log in with OpenID.

Now we can create an HTML form in a view; I created this simple view as login.html.erb within views/openid/new.html.erb:


<html>
<head>
    <title>Log in with OpenID</title>
</head>
<body>
    <% if not flash[:error].blank? %>
        <p><b><%= flash[:error] -%></b></p>
    <% end %>

    <% form_tag "/openid/create" do %>
      <%= text_field_tag "openid_url" %>
      <%= submit_tag "Log in with OpenID" %>
    <% end %>
</body>
</html>

Because everything between <% and %> in an ERb template is evaluated as Ruby code, we'll need to understand what is going on here. First, we create a form that is not connected to any object using the form_tag helper. (If the form were connected to an object, we would simply use the form helper.) We give it a URL of /openid, which we will discuss in a little bit, when we look at routing.

The form contains a single text field, whose name and id attributes both will be set to openid_url. Modern browsers recognize this name and use it to fill in an OpenID URL automatically. A submit button and a closing end tag complete the form.

Storing User Information

When we display this form in our browser, the user has one option—namely, to sign in with OpenID by entering a URL. The action (create) that is invoked has to find the user's OpenID server and redirect to that server. In order to do this, we need an instance of OpenID::Consumer, an object defined by the ruby-openid gem. Because we will continue to need this, we can create it as an instance variable:

def openid_consumer
 if @openid_consumer.blank?
   @openid_consumer =
     OpenID::Consumer.new(session,
           OpenID::Store::Filesystem.new("#{RAILS_ROOT}/tmp/openid"))
 end

 return @openid_consumer
end

Notice that we're storing the OpenID information on the filesystem, in the tmp directory under the root of our Rails project directory. This is a bad idea when you have multiple Web servers, but is certainly good enough for a small or beginning site.

Now that we have a method named openid_consumer and an instance variable named @openid_consumer, we can implement the create action, to which our HTML form is going to be submitted:

def create
 # Get the OpenID parameter
 openid_url = params[:openid_url]

 # Make sure we got something
 if openid_url.blank?
   flash[:error] = "No OpenID was entered; try again"
   redirect_to :back
   return
 end

 # Get an OpenID response
 openid_response = openid_consumer.begin openid_url

 home_url = url_for :controller => "openid", :action => "index"
 complete_url = url_for :controller => "openid", :action => "complete"
 openid_redirect_url = openid_response.redirect_url(home_url, complete_url)
 redirect_to openid_redirect_url

 return
end

In other words, we get the user's OpenID URL, and we check that it wasn't blank. Then, we use our instance of OpenID::Consumer to begin the OpenID login process, using open_consumer.begin, passing it the user's OpenID URL. If all goes well, this returns an instance of SuccessRequest, which also hands us the URL to which we should redirect the user. (If the request fails, the response will be a subclass of OpenIDStatus.)

Completing the Login Process

When we send the user to the user's OpenID server, we have to provide two different URLs as arguments: one that we're calling home_url, and the other that we're calling complete_url. The former is the root URL of our site; typically, it'll be a top-level URL. The latter, complete_url, tells the OpenID server to which URL the user should be redirected after logging in. In both cases, I use the built-in Rails url_for method, which constructs a URL out of a controller and action name.

When the user returns from the OpenID server, it will be to the URL indicated in complete_url. This means we have to define our complete method as well:

def complete
 home_url = url_for :controller => "openid", :action => "index"
 complete_url = url_for :controller => "openid", :action => "complete"

 openid_response = openid_consumer.complete(params, complete_url)

 session[:openid] = openid_response.identity_url
 flash[:error] = "You have been logged in as '#{session[:openid]}'"
 redirect_to :action => "new"
 return
end

After defining home_url and complete_url once again, we invoke the complete method on our instance of OpenID::Consumer. If the response is good (and here we assume that it is, ignoring the possibility that we might have gotten an instance of OpenIDStatus back). Obviously, your real-life applications should include such a check.

Sure enough, when we put all this in place, it works! We can enter our user ID into the HTML form. We get verified by the user's OpenID server, even if that means another redirect. And, we get the user verified with basic information.

Conclusion

OpenID is a simple but powerful idea that is slowly but surely transforming the way we manage identities on the Internet. A growing number of applications use OpenID, and it is becoming increasingly popular among users as well.

Adding OpenID to an application does not need to be complicated or difficult. As I show this month, incorporating OpenID into a Rails application requires understanding one particular Ruby object, namely OpenID::Consumer, and the odd, redirect-based, three-part OpenID login system specification.

Reuven M. Lerner, a longtime Web/database developer and consultant, is a PhD candidate in learning sciences at Northwestern University, studying on-line learning communities. He recently returned (with his wife and three children) to their home in Modi'in, Israel, after four years in the Chicago area.