How do I ignore the authenticity token for specific actions in Rails?
Ruby on-RailsRuby on-Rails Problem Overview
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?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
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 - Ruby on-Rails
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