ActiveRecord Based OpenID Store

A store is required by an OpenID server and optionally by the consumer to store associations, nonces, and auth key information across requests and processes. If rails is distributed across several machines, they must must all have access to the same OpenID store data, so the FilesystemStore won’t do.

This directory contains a plugin for connecting your OpenID enabled rails app to an ActiveRecord based OpenID store. The code here is copied from the library[https://github.com/openid/ruby-openid] examples (https://github.com/openid/ruby-openid/tree/master/examples/active_record_openid_store). All I did was move some things around, add a namespace and package it all up as a rails engine/plugin, with some conveniences, for use with Rails 3.

Usage

Just add it as a gem in your Gemfile

gem 'active_record_openid_store'

You will now have access to a rails generator to create the necessary migrations. Simply run:

rails g active_record_openid_store

Now that we have the migration we can create the necessary tables:

rake db:migrate

You should now have two extra tables, open_id_associations and open_id_nonces.

At this stage you’re essentially good to go, you can create a new store like this:

ActiveRecordOpenidStore::ActiveRecordStore.new

You can do this anywhere in your Rails app.

What about garbage collection?

Adding the active_record_openid_store gem to your Gemfile also gives you access to the openid:gc rake task. You may use this task at any time to clean up any expired nonces and associations.

rake openid:gc

This task isn’t doing anything fancy under the hood, it simply calls the cleanup method of the active record store (i.e.: ActiveRecordOpenidStore::ActiveRecordStore.new.cleanup)

Example With Omniauth

Let’s say you’re using omniauth and you’re also using Google OpenID to authenticate your users. You want to configure Google OpenID to use the ActiveRecord OpenID store. Given that you’ve followed the instructions above to add the gem and create the tables, you would configure Google OpenID like this.

In your config/initializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :openid, :store => ActiveRecordOpenidStore::ActiveRecordStore.new, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'
end

Having done this, if you go to /auth/google (as per how omniauth works) you will find that your associations and nonces are being stored in the database. Sweet!