LoginSignup
24
23

More than 3 years have passed since last update.

Rails で CSRF トークンの検証を制御する

Last updated at Posted at 2019-10-11

本記事は、以下ブログに投稿した記事のクロス投稿となります。
https://lanchester-tech-blog.hatenablog.com/entry/2019/10/15/135357


特定のコントローラで検証を無効化する

skip_forgery_protection を使います。
これは skip_before_action :verify_authenticity_token のラッパーなので only: :create 等のオプションを指定できます。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  skip_forgery_protection
end

大本のコントローラで指定して継承先のコントローラで重複して使用はできないので、その場合は protect_from_forgery with: :exception 等を明示的に指定します。

app/controllers/article_controller.rb
class ArticleController < ApplicationController
  protect_from_forgery with: :exception, only: :create

  def create
    # ...
  end
end

検証を完全に無効化する

検証そのものを行わないようにします。

config/application.rb
config.action_controller.allow_forgery_protection = false

警告だけを消す

検証は行って WARN のログは出さないようにします。

config/application.rb
config.action_controller.log_warning_on_csrf_failure = false

Rails 5.2 や 6 以降で null_session

rails 5.2 以降はデフォルトで protect_from_forgery with: :exception となるような変更(https://github.com/rails/rails/commit/ec4a836919c021c0a5cf9ebeebb4db5e02104a55)が入り、ApplicationController からは protect_from_forgery の記述が消されました。

ApplicationControllerprotect_from_forgery null: :session としても反映されないので以前のように with: :null_session を使いたい場合は以下のようにします。

config/application.rb
config.action_controller.default_protect_from_forgery = false
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # protect_from_forgery に with オプションを渡さない場合は with: :null_session と同等
  protect_from_forgery
end
24
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23