Rails raises an InvalidAuthenticityToken
when the CSRF token doesn't match. But, from reading the source, I can't figure out how this actually happens. I start by acking the tree for that class:
$ ack --ignore-dir=test InvalidAuthenticityToken
actionpack/lib/action_controller/metal/request_forgery_protection.rb
4: class InvalidAuthenticityToken < ActionControllerError #:nodoc:
17: # which will check the token and raise an ActionController::InvalidAuthenticityToken
actionpack/lib/action_dispatch/middleware/show_exceptions.rb
22: 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity
Only two hits, ignoring the comment. The first one is the class definition:
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
end
The second one is translating the exception into an HTTP status code. CSRF protection gets enabled by calling protect_from_forgery
in the controller, so let's look at that:
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
before_filter :verify_authenticity_token, options
end
It adds a filter:
def verify_authenticity_token
verified_request? || handle_unverified_request
end
Which calls this when verification fails:
def handle_unverified_request
reset_session
end
So how is InvalidAuthenticityToken
actually raised?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…