114

I have a rails app that serves some APIs to an iPhone application. I want to be able to simply post on a resource without minding on get the correct CSRF token. I tried some methods that I see here in stackoverflow but it seems they no longer work on rails 3.

Thank you for helping me.

Yuki Inoue
  • 3,569
  • 5
  • 34
  • 53
Simone D'Amico
  • 2,335
  • 3
  • 17
  • 21

3 Answers3

198

In the controller where you want to disable CSRF the check:

skip_before_action :verify_authenticity_token

Or to disable it for everything except a few methods:

skip_before_action :verify_authenticity_token, :except => [:update, :create]

Or to disable only specified methods:

skip_before_action :verify_authenticity_token, :only => [:custom_auth, :update]

More info: RoR Request Forgery Protection

Dorian
  • 22,759
  • 8
  • 120
  • 116
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • 2
    This is the correct answer for apps that have a mix of regular browser-accessible forms and API endpoints. The answer from Markus Proske would be correct if you were absolutely sure you were not going to have any browser-accessible forms in your app. – Asfand Qazi Jul 09 '14 at 10:44
  • Where exactly does this go? What if the controller part of some gem? – Throw Away Account Apr 05 '17 at 08:29
  • May I ask you if you can answer this very similar question? https://stackoverflow.com/questions/50159847/single-page-application-and-csrf-token –  May 06 '18 at 19:42
108

In Rails3 you can disable the csrf token in your controller for particular methods:

protect_from_forgery :except => :create 
Markus Proske
  • 3,356
  • 3
  • 24
  • 32
  • 12
    For anyone reading, note that this is what should go in `ApplicationController`. Mike Lewis' response below (`skip_before_filter :verify_authenticity_token`) is how to disable it on per-controller basis, assuming that controller inherits from `ApplicationController`. – NudeCanalTroll Feb 16 '13 at 21:04
  • Seems this is unsafe http://stackoverflow.com/questions/10676018/security-safe-to-disable-csrf-tokens-for-json-rails-calls. What do you think? is it? – sites May 13 '13 at 03:49
  • @NudeCanalTroll you mean putting this in the controller where I want it wont work? – DivinesLight May 28 '13 at 10:27
  • May I ask you if you can answer this very similar question? https://stackoverflow.com/questions/50159847/single-page-application-and-csrf-token –  May 06 '18 at 19:43
33

With Rails 4, you now have the option to write in skip_before_action instead of skip_before_filter.

# Works in Rails 4 and 5
skip_before_action :verify_authenticity_token

or

# Works in Rails 3 and 4 (deprecated in Rails 4 and removed in Rails 5)
skip_before_filter :verify_authenticity_token
thank_you
  • 11,001
  • 19
  • 101
  • 185