187

When I have a specific action that I don't want to check the authenticity token on, how do I tell Rails to skip checking it?

edebill
  • 7,655
  • 5
  • 32
  • 31

2 Answers2

256

Rails 5.2+

You can use the same skip_before_action method listed below or a new method skip_forgery_protection which is a thin wrapper for skip_before_action :verify_authenticity_token

skip_forgery_protection

Rails 4+:

# entire controller
skip_before_action :verify_authenticity_token

# all actions except for :create, :update, :destroy
skip_before_action :verify_authenticity_token, except: [:create, :destroy]

# only specified actions - :create, :update, :destroy
skip_before_action :verify_authenticity_token, only: [:create, :destroy]

See all options @ api.rubyonrails.org


Rails 3 and below:

skip_before_filter :verify_authenticity_token
BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
edebill
  • 7,655
  • 5
  • 32
  • 31
  • for specific controller and specific action, use: skip_before_filter :verify_authenticity_token, :only=> :my_unprotected_action. I came here to find the answer to: is this a terrible idea? I'm looking to do this because an ajax response eats my session. – Danny Jun 10 '13 at 22:03
  • 9
    For rails 5.2, use `skip_forgery_protection`. See [API docs](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html#method-i-skip_forgery_protection). – Aaron Breckenridge Jun 13 '18 at 17:56
32

In Rails4 you use skip_before_action with except or only.

class UsersController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:create]
  skip_before_action :some_custom_action, except: [:new]

  def new
    # code
  end

  def create
    # code
  end

  protected
  def some_custom_action
    # code
  end
end
Epigene
  • 3,634
  • 1
  • 26
  • 31
  • Thanks for this. It helped me create [this answer](https://stackoverflow.com/a/66669446/313756) to a similar question. :) – lindes Mar 17 '21 at 08:33