codahale.com٭blog

Coda Hale lives in Berkeley, CA, where he writes about Ruby on Rails, usability, web design and development, and the occasional bit about bicycles.

Basic HTTP Authentication with Rails & simple_http_auth

The Problem: You’ve got a controller (or just a few actions) in your Rails app that you’d like to control access to, but don’t feel like dealing with some huge-ass plugin, generator, or engine (whatever the hell those are).

The Solution: simple_http_auth!

Install!

Got your baby wrapped up in a comfy blanket of Subversion?


./script/plugin install -x http://svn.codahale.com/simple_http_auth

Just wanna get yer authentication on?


./script/plugin install http://svn.codahale.com/simple_http_auth

Feeling all DIY-y?


cd my_rails_app/vendor/plugins
svn co http://svn.codahale.com/simple_http_auth

Configure!

Here’s the really choice bit: simple_http_auth is just that–simple. It doesn’t validate username or passwords for you, since that’s your job. It just provdes a nice, clean wrapper for HTTP Basic authentication.

Dig it:


class PenguinsController < ApplicationController

  requires_authentication :using => Proc.new{ |username, password| password == 'ponies!' },
                          :except => [:index],
                          :realm => 'Secret Magic Happy Cloud'

  def index
    # public things...
  end

  def secret_magic_happy_cloud
    # most secret things...
  end

end

Basically, you define an event handler (in this case, a Proc) which, given a username and password, returns true if the pair are valid, and false otherwise. Super cool feature: this event handler is executed within the instance of the controller, which means you get to access all the controller internals you’ve grown to love, like sessions! You can also specify a private or protected method of the controller by passing a Symbol:


  requires_authentication :using => :authenticate

This means that all the details of a user model (if you want one), how passwords are stored, etc., are all up to you. You get to choose the best way to build your app instead of trying to make do with someone else’s infrastructure.

Update: Logout!

You can now log users out:

class HappyMagicController < ApplicationController
  requires_authentication :using => :whatever,
                          :logout_on => :logout

  def logout
    # logout.rhtml will be displayed after the user logs out
  end
end

Woo!

More details can be found in the readme.

Have fun!

37 comments »