RailsでBASIC認証をさせる

( Rails )

Railsで手っ取り早くBASIC認証させるためのメモ

class BasicController < ApplicationController

  before_filter :basicauth

  def basicauth
    name = 'hoge'
    password = 'hohohohoho'
    msg = 'please input basic auth'
    authenticate_or_request_with_http_basic(msg) do |n,p|

      File.open("#{Rails.root}/public/password.txt", "r") {|f|
        f.each_line do |line|
          arr = line.split(":")
          name = arr[0]
          password = arr[1]
          if n == name && p.crypt(password[0,2]) == password
            logger.debug("ok!!!")
          else
            return false
          end
        end
      }
    end
  end
end

うん、簡単ですね。Zendのときでもこんなに完結にはかけなかったものです。。

「authenticate_or_request_with_http_basic」すばらしい!!