加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4删除按钮将我注销并导致“无法验证CSRF

发布时间:2020-12-17 02:48:27 所属栏目:百科 来源:网络整理
导读:我正在运行Rails 4.2,Devise 3.4.1和CanCan 1.6.10.当我尝试通过标准删除按钮删除资源时,如下所示,我退出并重定向到登录页面. a data-confirm =“你确定吗?” class =“btn-alert”rel =“nofollow”data-method =“delete”href =“/ admin / lots / 6”删
我正在运行Rails 4.2,Devise 3.4.1和CanCan 1.6.10.当我尝试通过标准删除按钮删除资源时,如下所示,我退出并重定向到登录页面.

< a data-confirm =“你确定吗?” class =“btn-alert”rel =“nofollow”data-method =“delete”href =“/ admin / lots / 6”>删除< / a>

我的开发日志告诉我这是因为它“无法验证CSRF令牌的真实性”.我似乎能够让它工作的唯一方法是从删除按钮更改为发布到删除操作的表单,但这有点愚蠢.我在其他Rails 4应用程序中完成了这个,所以我很确定我做得对.

index.html.erb

<% if can? :destroy,lot %>
   <%= link_to "Delete",admin_lot_path(lot.id),method: :delete,data: {confirm: "Are you sure?"},class: 'btn-alert' %>
<% end %>

lots_controller.rb

class Admin::LotsController < ApplicationController
  before_filter :authenticate_user!
  load_and_authorize_resource

  def destroy
    @lot.destroy
    redirect_to admin_lots_path,notice: "Lot was successfully removed."
  end
end`

就像我说的那样,用表格替换按钮似乎有效,但这并不理想.

<%= form_for([:admin,lot],method: :delete) do |f| %>
   <%= f.submit value: "Delete",class: 'btn-standard',data: {confirm: "Are you sure?"} %>
<% end %>

如果我注释掉before_filter:authenticate_user!和它工作的控制器的load_and_authorize_resource.我假设csrf令牌不会像这样在表单中一起发送.

有没有人对我能尝试什么有任何想法?如果它有用,愿意发布更多代码.这发生在我的应用程序btw中的所有删除.

更新:这是来自development.log的片段

Started DELETE "/admin/lots/6" for 127.0.0.1 at 2015-05-26 15:03:22 -0500
Processing by Admin::LotsController#destroy as HTML
  Parameters: {"id"=>"6"}
Can't verify CSRF token authenticity

解决方法

使用button_to而不是link_to.

button_to "Delete",class: 'btn-alert'

link_to生成此HTML,缺少真实性令牌,

<a data-confirm="Are you sure?" class="btn-alert" rel="nofollow" data-method="delete" href="/admin/lots/6">Delete</a>

而button_to产生

<form class="button_to" method="post" action="/admin/lots/6">
    <input type="hidden" name="_method" value="delete">
    <input data-confirm="Are you sure?" class="btn-alert" type="submit" value="Delete">
    <input type="hidden" name="authenticity_token" value="1QajBKKUzoEtUqi6ZX8DsQtT9BfvKY/WVXAr4lu4qb+iLGMkLlsviNcctlGxyq+VrsMa+U9vmb4PAdaRFDKZVQ==">
</form>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读