我有一个由Ajax.InPlaceEditor或InPlaceCollectionEditor生成的AJAX请求触发的操作,如下所示:
new Ajax.InPlaceCollectionEditor('agent_email','inspections/<%= @inspection.id %>/update_field',{ collection: [<% @agents.each do |agent| %> '<%= agent.email %>',<% end %>],okText: 'Update',cancelText: 'Never mind',savingText: 'Updating...' });
在另一端,该操作包含:
def update_field --some code here-- if success puts "stored change" render :text => result else puts "did note change store" render :text => inspection.errors.to_json,:status => 500 end end
一旦到达任何渲染方法,会话就会到期,并且下次用户发送请求时,Devise会将它们发送到登录页面.
尽管我正在免除update_field的身份验证(before_filter:authenticate_user!,:except =>:update_field),但会话仍在重置.
我在Devise session immediately expiring on .js call [AJAX]的一个非常相似的问题上看了答案,但它并没有解决我的特殊问题.
有任何想法吗?
通过从
http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails(prototype-snippet.js)获取代码,我得到了这个工作:
原文链接:https://www.f2er.com/ajax/160200.html/* * Registers a callback which copies the csrf token into the * X-CSRF-Token header with each ajax request. Necessary to * work with rails applications which have fixed * CVE-2011-0447 */ Ajax.Responders.register({ onCreate: function(request) { var csrf_Meta_tag = $$('Meta[name=csrf-token]')[0]; if (csrf_Meta_tag) { var header = 'X-CSRF-Token',token = csrf_Meta_tag.readAttribute('content'); if (!request.options.requestHeaders) { request.options.requestHeaders = {}; } request.options.requestHeaders[header] = token; } } });
…在我的application.html.erb中的Javascript块中:
<script type="text/javascript"> (... the code from above) </script>
另外别忘了添加:
<%= csrf_Meta_tag %>
在顶部的同一文件中(如果还没有).
文件“CSRF Protection Bypass in Ruby on Rails”解释了为什么这样做.