ruby-on-rails - 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%>
解决方案
正如其他人指出的那样,跳过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
推荐阅读
- visual-studio-2017 - 关闭 c# 格式规则(缩进、换行、间距)
- ibm-datapower - IBM APIConnect 是否与 3rd 方网关一起使用
- c++ - 如何区分宏 func 和函数 func 没有任何歧义?
- docker - Docker-compose 错误:无法限制容器间通信
- c# - Xamarin.Android 代码编译
- typescript - Typescript 中的子类化
- asp.net - 如何使用 asp.net mvc 5 配置 hdiv
- git - Git/Gitflow 在同一个文件中的不同功能
- amazon-dynamodb - Dynamo DB 属性类型 boolean
- c# - 提高性能或代码调优