首页 > 解决方案 > ActionController::InvalidAuthenticityToken in PostsController#create

问题描述

在我的 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%>

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

解决方案


正如其他人指出的那样,跳过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

推荐阅读