相关疑难解决方法(0)

Rails CSRF保护如何运作?

InvalidAuthenticityToken当CSRF令牌不匹配时,Rails会引发一个.但是,从阅读来源,我无法弄清楚这是如何实际发生的.我首先为该类修饰树:

$ 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
Run Code Online (Sandbox Code Playgroud)

只有两次点击,忽略了评论.第一个是类定义:

class InvalidAuthenticityToken < ActionControllerError #:nodoc:
end
Run Code Online (Sandbox Code Playgroud)

第二个是将异常转换为HTTP状态代码.通过调用protect_from_forgery控制器来启用CSRF保护,让我们看一下:

def protect_from_forgery(options = {})
  self.request_forgery_protection_token ||= :authenticity_token
  before_filter :verify_authenticity_token, options
end
Run Code Online (Sandbox Code Playgroud)

它添加了一个过滤器:

def verify_authenticity_token
  verified_request? || handle_unverified_request
end
Run Code Online (Sandbox Code Playgroud)

验证失败时会调用此函数:

def handle_unverified_request
  reset_session
end
Run Code Online (Sandbox Code Playgroud)

那么InvalidAuthenticityToken实际上是如何提出的?

ruby ruby-on-rails ruby-on-rails-3

21
推荐指数
2
解决办法
1万
查看次数

标签 统计

ruby ×1

ruby-on-rails ×1

ruby-on-rails-3 ×1