title: How does Rails CSRF protection work?
body: <p>Rails raises an <code>InvalidAuthenticityToken</code> when the CSRF token doesn't match.  But, from reading the <a href="https://github.com/rails/rails" rel="noreferrer">source</a>, I can't figure out how this actually happens.  I start by acking the tree for that class:</p>
  
  <pre><code>$ ack --ignore-dir=test InvalidAuthenticityToken
  
  actionpack/lib/action_controller/metal/request_forgery_protection.rb
  4:  class InvalidAuthenticityToken &lt; ActionControllerError #:nodoc:
  17:  # which will check the token and raise an ActionController::InvalidAuthenticityToken
  
  actionpack/lib/action_dispatch/middleware/show_exceptions.rb
  22:      'ActionController::InvalidAuthenticityToken' =&gt; :unprocessable_entity
  </code></pre>
  
  <p>Only two hits, ignoring the comment.  The first one is the class definition:</p>
  
  <pre><code>class InvalidAuthenticityToken &lt; ActionControllerError #:nodoc:
  end
  </code></pre>
  
  <p>The second one is translating the exception into an HTTP status code.  CSRF protection gets enabled by calling <code>protect_from_forgery</code> in the controller, so let's look at that:</p>
  
  <pre><code>def protect_from_forgery(options = {})
    self.request_forgery_protection_token ||= :authenticity_token
    before_filter :verify_authenticity_token, options
  end
  </code></pre>
  
  <p>It adds a filter:</p>
  
  <pre><code>def verify_authenticity_token
    verified_request? || handle_unverified_request
  end
  </code></pre>
  
  <p>Which calls this when verification fails:</p>
  
  <pre><code>def handle_unverified_request
    reset_session
  end
  </code></pre>
  
  <p>So how is <code>InvalidAuthenticityToken</code> actually raised?</p>