设计+滑轨3.0.4 AJAX请求之后结束会话
问题描述:
我已经通过Ajax.InPlaceEditor
或InPlaceCollectionEditor
产生这样一个AJAX请求触发的动作:设计+滑轨3.0.4 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会将它们发送到页面上的登录。
尽管我正在免除身份验证(before_filter :authenticate_user!, :except => :update_field
)中的update_field,但会话仍在重置。
我在Devise session immediately expiring on .js call [AJAX]的一个非常类似的问题上看过答案,但它不能解决我的特殊问题。
任何想法?
答
我这通过获取代码http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails工作(原型snippet.js):Javascript脚本块内我application.html.erb
/*
* 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;
}
}
});
...:
<script type="text/javascript">
(... the code from above)
</script>
也不要忘记加一句:
<%= csrf_meta_tag %>
朝顶部相同的文件(如果尚未有)。
该文件“CSRF Protection Bypass in Ruby on Rails”解释了它的工作原理。