RailsでBasic認証をする

REST対応のためか、Rails-2.0.2以降では標準でBasic認証がサポートされている。
使い方は極めて簡単。
before_filterで、authenticate_or_request_with_http_basicを記述すれば良い。

class FooController < ApplicationController
  USER_NAME, PASSWORD = "user", "pass"
  before_filter :authenticate
  def index
    render_text "test"
  end
  private 
  def authenticate
    authenticate_or_request_with_http_basic do |user_name, password|
      user_name == USER_NAME && password == PASSWORD
    end
  end
end

これほど簡単とは。さすがRails