How do I ignore the authenticity token for specific actions in Rails?

Solution 1:

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

Solution 2:

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