概要
開発環境でRailsアプリを作成している時に、簡単なセキュリティ対策のため、basic認証を行えないか調査しました。その結果を記載します。
詳細
実装
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :basic
  
  private
  def basic
    authenticate_or_request_with_http_basic do |name, password|
      name == "test" && password == "123456"
    end
  end
end
解説
application_controller.rb
共通のコントローラーの処理を記載するファイル。
before_action :<アクション名>
全てのアクションが実行される前に行う処理を記載する。
また、引数として渡すアクション名はシンボルとして渡す。
  private
  def アクション名
    authenticate_or_request_with_http_basic do |name, password|
      name == "test" && password == "123456"
    end
  end
nameにログインユーザ名、passwordにパスワードを記載する。