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

Ruby on-Rails

Ruby 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionedebillView Question on Stackoverflow
Solution 1 - Ruby on-RailsedebillView Answer on Stackoverflow
Solution 2 - Ruby on-RailsEpigeneView Answer on Stackoverflow