Chr*_*fer 1 exception-handling ruby-on-rails csrf
我有一个Rails网络应用程序,用户可以使用一些表单进行评论等.他们经常被垃圾邮件发送者用来尝试创建垃圾评论.没什么新鲜的.
有时我会遇到导致ActionController :: InvalidAuthenticityToken异常的CSRF-hack尝试.这种情况发生了很多,我想拯救并将用户/机器人发送到"你没有评论"页面.
事实证明这是一个棘手的例外,因为我不能自己重新创建错误.当模型(由表单创建)被保存但是它没有捕获异常时,我首先在#create中进行了拯救.为了做到这一点,我考虑让它覆盖整个控制器部分,但这似乎超过顶部.
我的两个问题:
有没有办法自己重新创建一个ActionController :: InvalidAuthenticityToken错误,所以我可以测试一下吗?
什么时候提出异常?在.save期间?在Comment.new?基本上,我应该在哪里开始/救援?
谢谢!
您可以在控制器中解除此异常.设置此方法的一种方法是在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
Run Code Online (Sandbox Code Playgroud)
您还可以在控制器操作中本地捕获异常.
def create
begin
# Create your comment
rescue ActionController::InvalidAuthenticityToken
# Render your last view with some error text.
end
end
Run Code Online (Sandbox Code Playgroud)
raise ActionController::InvalidAuthenticityToken
如果要测试它,可以在操作中添加内容.