ActionController::InvalidAuthenticityToken 解决办法

来源:互联网 发布:淘宝退货没有售后卡 编辑:程序博客网 时间:2024/05/09 20:40

 

ActionController::InvalidAuthenticityToken 异常一般出现出现在手写的html form 标签和Ajax请求中,为什么会出现这个异常呢,这是从rails 2.0 开始包含的一个新功能,目的在于防止CSRF(Cross-Site Request Forgery)攻击.
rails 为了保证当前的请求是来自自己的请求,而不是通过其他网站伪造的请求,都会在生成的form 里加入一个隐藏的值

<input type="hidden" value="457a1e93c3a23ec2c67f1dc468bde6a4a5539610" name="authenticity_token"/> 
生成的ajax代码:

onsubmit="new Ajax.Updater('div', '/cotroller1/action1/1', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)
+ '&authenticity_token=' + encodeURIComponent('457a1e93c3a23ec2c67f1dc468bde6a4a5539610')})

从上面的代码里可以看出关键是要向action 传递authenticity_token这个参数和正确的值

当然如果你认为你的action确实不需要验证,那可以这么写:(在application中写)

#除了index,controller里的其他action都需要验证
protect_from_forgery :except => :index

#只有index需要验证
protect_from_forgery :only => :index  

如果是在ajax里可以在服务端生成好需要传入的字符串

"'#{request_forgery_protection_token}='
+ encodeURIComponent('#{escape_javascript
 form_authenticity_token}')"

原创粉丝点击