我有两个名为 Post 和 PostComment 的模型。
目前,我使用 hidden_field
表单助手发送额外的数据,例如发布时间、评论发布者的用户 ID 以及发表评论的帖子 ID,如下所示:
<%= f.hidden_field :posttime, value: Time.now.getutc %>
<%= f.hidden_field :post_id, value: @post.id %>
<%= f.hidden_field :user_id, value: current_user.id %>
我突然意识到我可以使用浏览器的检查器更改这些值,因此这是一个安全漏洞。那么如何安全地发送这些参数呢?
最佳答案
通常这些值不会通过表单传递,而是通过使用嵌套 URL 的 URL 进行访问(在此处了解如何操作:http://guides.rubyonrails.org/routing.html)
例如,要使用 post_id
形式的网址,您需要设置评论路由以包含该帖子,例如您将拥有 new_post_comment_path
并且在您的 Controller 中您可以访问params[:post_id]
而不通过表单传递它。
你的表单会变成这样:
<% form_for [@post, Comment.new] do |f| %>
...
re: user_id
- 绝对不要以表单的形式传递它,你说得很对,这是一个很大的安全问题(人们可以为其他人添加评论!)只需通过以下方式访问它您 Controller 中的身份验证方法(即 current_user
)。
您最终会在 Controller 中得到类似的内容,例如:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params)
@comment.user = current_user
if @comment.save
redirect_to [@post, @comment]
else
render_action :new
end
end
private
# Don't forget to use require/permit to make sure the user can't
# fake up the user/post id fields themselves out of whole-cloth
def comment_params
# or whatever your permitted comment-fields are.
params.require(:comment).permit(:content)
end
关于ruby-on-rails - Rails 在不使用hidden_field 标记的情况下将额外参数传递给请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841097/