当CSRF令牌不匹配时,Rails引发InvalidAuthenticityToken
。但是,从阅读source,我无法弄清楚这是如何发生的。我从acking那棵树开始:Rails CSRF保护如何工作?
$ 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
只有两个命中,忽略注释。第一个是类定义:
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
end
第二个是将异常转换为HTTP状态代码。 CSRF保护得到由控制器调用protect_from_forgery
启用,所以让我们看看:
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
before_filter :verify_authenticity_token, options
end
它增加了一个过滤器:
def verify_authenticity_token
verified_request? || handle_unverified_request
end
当验证失败调用该:
def handle_unverified_request
reset_session
end
那么InvalidAuthenticityToken
实际上是如何提升的?
谢谢!这就是我运行3.0.3但读取master的源代码所得到的结果。对这一变化背后原因的很好解释 - 甚至比官方博客文章中的更好。 – 2011-02-15 23:45:22