Rails:用户在使用 :remote => true 销毁不相关的对象后注销

2024-03-18

我正在跟进http://railscasts.com/episodes/250-authentication-from-scratch http://railscasts.com/episodes/250-authentication-from-scratch用于简单的身份验证。它按预期工作。我的应用程序中有一个模型,其中包含以下内容partial :

<%= content_tag_for(:li, post) do %>
  <%= link_to 'Delete', post, :confirm => 'Are you sure?', :method => :delete, :remote => true %>
<% end %>

内称为index.html.erb如下:

<%= render :partial => @posts.reverse %>

The destroy.js.erb如下,如果对象被成功销毁,则调用该函数。

$('#<%= dom_id(@post) %>').css('background', 'red');
$('#<%= dom_id(@post) %>').hide();

单击时delete按钮,post对象被正确删除并且destroy.js.erb也正确渲染。但不知何故,用户已注销。以下是我的代码posts_controller.rb :

  def destroy
    logger.error 'in destroy'
    @post = Job.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.xml  { head :ok }
      format.js
    end
  end

有任何线索为什么会出现这种行为吗?

而且,如果我删除:remote => true来自delete链接,然后用户保持登录状态。我在destroy方法用于session在这两种情况下都不会被调用,但是如果 ':remote=>true那么会议就不知何故搞砸了。在检查 cookie 时,我发现 cookie 没有被破坏,但是当destroy方法上posts叫做。不知道为什么会发生这种情况。


听起来你正在碰到一个旨在防止跨站请求伪造 http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf。添加:remote => true导致请求在没有 CSRF 安全令牌的情况下通过 ajax 提交,因此 Rails 会破坏会话,因为它认为这是 CSRF 攻击。为了解决这个问题,您有以下几种选择:

  1. 一个快速但肮脏(且不安全)的解决方案是关闭该请求的安全检查。为此,请将此行添加到控制器的顶部:

    skip_before_filter :verify_authenticity_token, :only => [:destroy]

  2. 更安全的解决方案是提交CSRF带有 AJAX 调用的令牌。我认为如果您将远程链接更改为button_to。阅读更多here http://guides.rubyonrails.org/ajax_on_rails.html.

    <%= button_to 'Delete', post, :confirm => 'Are you sure?', :method => :delete, :remote => true %>

  3. 您还可以使用 cookies 来存储 current_user 而不是会话。这样做的安全影响将取决于您的应用程序的详细信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails:用户在使用 :remote => true 销毁不相关的对象后注销 的相关文章

随机推荐