authlogic: Another Take on Rails Authentication

There are certainly plenty of plugins available to handle authentication in Rails, with perhaps the most commonly-used being Restful Authentication. But there's always room for one more, and the latest I've run across is Ben Johnson's authlogic. It takes a fresh approach to the problem space, with one big advantage over many existing solutions: because it's a pure plugin rather than a generator, it doesn't litter your application with a ton of code.

The key to making this approach work is that you need to define a special user session model that inherits from authlogic's internals, rather than from ActiveRecord::Base :

class UserSession < Authlogic :: Session :: Base end

With that in place, you can use the regular Rails generator to spin up a controller for user sessions, and write "natural" code. For instance, logging a user in is just a matter of running @user_session = UserSession.new(params[:user_session]) . Similarly, destroying a UserSession instance logs the current user out.

In addition to the source code, you can explore an Authlogic Setup Tutorial or play with an implemented example online. I haven't used authlogic in a client project yet, but after experimenting with it in some test code, it's definitely on my list for the next time I need to roll out authentication as a feature.

Tweet This Post