【问题标题】:Rails: Test against and handle ActionController::InvalidAuthenticityTokenRails:测试和处理 ActionController::InvalidAuthenticityToken
【发布时间】:2015-11-15 00:06:53
【问题描述】:
我有一个 Rails Web 应用程序,其中包含一些用户可以用来评论等的表单。垃圾邮件发送者经常使用它们来创建垃圾邮件 cmets。没什么新鲜的。
有时我会收到导致 ActionController::InvalidAuthenticityToken 异常的 CSRF-hack 尝试。这种情况经常发生,我想拯救用户/机器人并将其发送到“您未能发表评论”页面。
这被证明是一个难以捕捉的异常,因为我自己无法重新创建错误。当要保存模型(由表单创建)但它没有捕获异常时,我首先在#create 中进行了救援。为了做到这一点,我考虑让它覆盖整个控制器部分,但这似乎超出了顶部。
我的两个问题:
有没有办法自己重新创建 ActionController::InvalidAuthenticityToken 错误,让我测试一下?
何时引发异常?在 .save?在 Comment.new 上?基本上,我应该把我的开始/救援放在哪里?
谢谢!
【问题讨论】:
标签:
ruby-on-rails
exception-handling
csrf
【解决方案1】:
您可以在控制器中从这个异常中解救出来。一种设置方法是在 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。