【问题标题】:ActionController::InvalidAuthenticityToken in PostsController#createActionController::InvalidAuthenticityToken 在 PostsController#create
【发布时间】:2018-06-04 10:52:50
【问题描述】:

在我的 Rails 博客应用程序中,当我尝试提交新帖子的表单时收到此错误消息:

PostsController#create 中的 ActionController::InvalidAuthenticityToken ActionController::InvalidAuthenticityToken 提取的源代码(在 #211 行附近):

      def handle_unverified_request
        raise ActionController::InvalidAuthenticityToken
      end
    end
  end

这是我的 posts_controller.rb 文件:

class PostsController < ApplicationController
  def index
  end

  def new
  end

  def create
    @post=Post.new(post_params)
    @post.save

    redirect_to @post
  end

  def show
    @show=Post.find(params[:id])
  end

  private
    def post_params
      params.require(:post).permit(:title,:body)
    end
end

这是我的表单代码:

<font color="#BD004B"><h1>New Post<br></h1></font>

<%=form_for :post, url: posts_path do |f|%>
  <p>
  <%=f.label :title%><br>
  <%=f.text_field :title%>
  </p>
  <p>
  <%=f.label :body%><br>
  <%=f.text_area :body%>
  </p>
  <p>
    <%=f.submit%>
  </p>
<%end%>

【问题讨论】:

  • 你能分享你的表单代码吗?
  • 它可能是视图的缺失部分或控制器中缺失的回调方法,它跳过了发布/放置/删除请求的真实性操作。所以请按照@D1ceWard 的要求分享查看代码,我也希望看到application_controller.rb 代码。
  • @D1ceWard 我已经发布了表单代码
  • @radoAngelov 我已经发布了表单代码
  • @radoAngelov skip_before_action :verify_authenticity_token 跳过令牌验证,这是一个安全问题,顺便说一句不是解决方案,我们需要更多信息,例如 new/_form 的全部内容,与 post 和 rails 版本相关的路由,因为对于现在一切看起来都很好

标签: ruby-on-rails ruby ruby-on-rails-5.2


【解决方案1】:

正如其他人指出的那样,跳过verify_authenticity_token 不是一种选择,并且会在您的应用程序的安全性中打开大漏洞。

异常通常出现在两种情况下:您的会话已用完,我们的表单是通过没有 csrf_meta_tags 的 ajax 发送的。

该问题的正确解决方案是拯救异常并重置用户的会话,如下所示:

rescue_from ActionController::InvalidAuthenticityToken do
  logger.info "Compromised session found."
  reset_session
  flash[:error] = "You're session has expired"
  redirect_to root_path # or new_user_session_path
end

【讨论】:

  • 我从我的application_controller.rb 文件中删除了它,我的应用程序的功能没有任何区别,所以我把它排除在外
猜你喜欢
  • 2014-01-19
  • 2019-07-15
  • 2018-11-02
  • 2015-07-20
  • 2011-03-22
  • 2018-11-27
  • 2015-11-23
  • 2021-12-20
  • 2017-11-13
相关资源
最近更新 更多