Rails:测试并处理ActionController :: InvalidAuthenticityToken

时间:2015-08-21 06:22:31

标签: ruby-on-rails exception-handling csrf

我有一个Rails网络应用程序,其中包含一些用户可以用来评论的表单等。他们经常被垃圾邮件发送者用来尝试创建垃圾评论。没什么新鲜的。

有时我会遇到导致ActionController :: InvalidAuthenticityToken异常的CSRF-hack尝试。这种情况发生了很多,我想拯救并将用户/机器人发送给"你没有评论" -page。

这已经证明是一个棘手的例外,因为我不能自己重新创建错误。当模型(由表单创建)被保存但我没有捕获异常时,我首先在#create中进行了拯救。为了做到这一点,我考虑让它覆盖整个控制器部分,但这似乎超过顶部。

我的两个问题:

  1. 有没有办法自己重新创建一个ActionController :: InvalidAuthenticityToken错误,所以我可以测试一下吗?

  2. 什么时候引发异常?在.save期间?在Comment.new?基本上,我应该把我的开始/救援放在哪里?

  3. 谢谢!

1 个答案:

答案 0 :(得分:5)

您可以在控制器中解除此异常。设置此方法的一种方法是在ApplicationController中添加一个救援。

class ApplicationController < ActionController::Base    
  rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_auth_token

  private

  def record_not_found
    render :text => "You failed to comment", :status => 422
  end

end

您也可以在控制器操作中本地捕获异常。

def create
  begin
    # Create your comment
  rescue ActionController::InvalidAuthenticityToken
    # Render your last view with some error text.
  end
end

如果您想对其进行测试,可以在操作中添加raise ActionController::InvalidAuthenticityToken