问题描述
我有一个由 Ajax.InPlaceEditor
或 InPlaceCollectionEditor
生成的 AJAX 请求触发的操作,如下所示:
I have an action triggered by an AJAX request generated by Ajax.InPlaceEditor
or InPlaceCollectionEditor
like this:
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 会将它们发送到登录页面.
Once any of the render methods are reached, the session expires, and next time the user send a request, Devise sends them to the logon on page.
即使我从身份验证中免除 update_field (before_filter :authenticate_user!, :except => :update_field
),会话仍在重置.
Even though I am exempting update_field from authentication (before_filter :authenticate_user!, :except => :update_field
), the session is still getting reset.
我在设计中查看了一个非常相似的问题的答案session 在 .js 调用 [AJAX] 时立即过期,但它没有解决我的特定问题.
I have looked at the answer at a very similar question at Devise session immediately expiring on .js call [AJAX], but it is not solving my particular problem.
有什么想法吗?
推荐答案
我通过从 http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails(原型片段.js):
I got this to work by getting the code from http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails (prototype-snippet.js):
/*
* 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 块中:
... within a Javascript block in my application.html.erb:
<script type="text/javascript">
(... the code from above)
</script>
另外不要忘记添加:
<%= csrf_meta_tag %>
在顶部的同一个文件中(如果还没有).
in the same file towards the top (if not already there).
文档Ruby on Rails 中的 CSRF 保护绕过"解释了为什么会这样.
The document "CSRF Protection Bypass in Ruby on Rails" explains why this works.
这篇关于Devise + Rails 3.0.4 在 AJAX 请求后结束会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!