Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active December 26, 2021 00:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save maxivak/a25957942b6c21a41acd to your computer and use it in GitHub Desktop.
Save maxivak/a25957942b6c21a41acd to your computer and use it in GitHub Desktop.
Rails. Skip the authenticity token check if its a json request

skip the authenticity token check for a json request

if you got this error while requesting the application via JSON request:

exception ActionController::InvalidAuthenticityToken

backtrace":"[\"/home/uadmin/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.4/lib/action_controller/metal/request_forgery_protection.rb:181:in `handle_unverified_request'\", 
\"/home/uadmin/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.4/lib/action_controller/metal/request_forgery_protection.rb:209:in `handle_unverified_request'\", 
...

modify your controller:

class ApplicationController < ActionController::Base
  skip_before_filter :verify_authenticity_token, if: :json_request?

  def json_request?
    request.format.json?
  end
end

@Al-un
Copy link

Al-un commented Oct 21, 2018

For Rails 5+ users, skip_before_filter has been deprecated in favor of skip_before_action. Source on Rails 4.2 release notes

@alexventuraio
Copy link

alexventuraio commented Feb 11, 2020

@Al-un @maxivak Is it the proper way to go when you have Rails API controllers handling JSON requests from a ReactJs app? I mean, is it secure to remove the verify_authenticity_token since you are in an API app?

@Al-un
Copy link

Al-un commented Apr 9, 2020

@alexventuraio,
It's been a while I have done any Rails stuff so I forgot the exact usage of the authenticity token. I compare it with a kind of "CSRF" check. If you use a React App, it can be served from a different domain than your API. Authentication must then be checked by a token.

@niedfelj
Copy link

It's much better to do this

protect_from_forgery with: :null_session

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment