Rails 4 Authenticity Token

I think I just figured it out. I changed the (new) default

protect_from_forgery with: :exception

to

protect_from_forgery with: :null_session

as per the comment in ApplicationController.

# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.

You can see the difference by looking at the source for request_forgery_protecton.rb, or, more specifically, the following lines:

In Rails 3.2:

# This is the method that defines the application behavior when a request is found to be unverified.
# By default, \Rails resets the session when it finds an unverified request.
def handle_unverified_request
  reset_session
end

In Rails 4:

def handle_unverified_request
  forgery_protection_strategy.new(self).handle_unverified_request
end

Which will call the following:

def handle_unverified_request
  raise ActionController::InvalidAuthenticityToken
end

Leave a Comment