LoginSignup
96
98

More than 5 years have passed since last update.

Rails4のCSRF対策で「Can't verify CSRF token authenticity」エラー

Posted at

Rails4だとCSRF対策が非常に優秀です。

デフォルトで「ApplicationController」には「protect_from_forgery with: :exception」の記述があります。

CSRFの仕組みについては以下の記述が参考になります。

★RailsのCSRF対策の仕組みについて
 http://shindolog.hatenablog.com/entry/2014/09/01/013840

また、「protect_from_forgery」については以下の記述が参考になります。

★Rails 4.0だとCSRFトークンでエラーになる
 http://qiita.com/naoty_k/items/b40b13735fd7f06f8cb7

そしてこちらですが、安易な「a」タグや外部のサイトからの接続の際に「Can't verify CSRF token authenticity」エラーというエラーが出てしまいます。(動作としてはとても正しいです。)

対処を見ると「ApplicationController」を「protect_from_forgery with: :null_session」とするというのも見受けられますが、これだとCSRF対策が根本的にNGなので、できれば外部からのAPIを受ける特定アクションのみ除外とする方が正しいので、方法は以下になります。

・Testコントローラのsampleアクションを除外したいとき。

TestController.rb
class TestController < ApplicationController
  protect_from_forgery :except => [:sample]

  def sample
    ## 処理
  end
end

無事、外部からのリクエストも処理できました。

96
98
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
96
98