ましめも

技術系メモ

Railsのprotect_from_forgeryは必ずしも外部からのリクエストから守ってくれない

Railsお勉強中。ためしにログイン不要な掲示板作ってる
https://github.com/mashijp/railsboard

外部からトピック作成やレス作成をできないように対策することを「CSRF対策」っていうのかと思っていたが、ログイン前提じゃないとCSRFじゃないらしい…知らんかった…。Railsのprotect_from_forgeryはトークンのない更新系アクセスがあった場合セッションを消すだけなので、ログイン不要なサイトだと意味がない(警視庁等の通報ページも同様)。
※詳しくは» Rails3のprotect_from_forgeryはトークンの検証NGの場合にreset_sessionする TECHSCORE BLOGを参照


どうしようかなと頭を抱えていたけど、Railsソースコード(request_forgery_protection.rb)読んでたら簡単にオーバーライドできることが判明

      # This is the method that defines the application behavior when a request is found to be unverified.
      # By default, \Rails resets the session when it finds an unverified request.
      def handle_unverified_request
        reset_session
      end

ということでoverrideしました!

class ApplicationController < ActionController::Base
  protect_from_forgery

  protected
  def handle_unverified_request
    raise Exception("なんやこれ")
  end
end

https://github.com/mashijp/railsboard/commit/31d67c7803770219b8461a0266e46f76392f72b4
↑あとでまじめにやる

(タイトルは煽り)