【发布时间】:2011-06-27 09:15:06
【问题描述】:
当 CSRF 令牌不匹配时,Rails 会引发 InvalidAuthenticityToken。但是,通过阅读source,我无法弄清楚这实际上是如何发生的。我首先确认该类的树:
$ 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到底是怎么升的?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3