简体   繁体   English

借助rails before_action,您如何防止恶意用户创建,更新,编辑和删除

[英]With rails before_action how can you protect from malicious users for create / update / edit and delete

The rails before action seems useful for setting a variable shared by a number of actions in a controller. 动作之前的轨道对于设置控制器中多个动作共享的变量似乎很有用。

But isn't the default implementation of the set_post that we see commonly on tutorials etc open to an attack by a malicious user? 但是,我们通常在教程等中经常看到的set_post的默认实现是否不会受到恶意用户的攻击?

If we take a controller like this: 如果我们采用这样的控制器:

PostsController < Application Controller
  before_action :set_post , only: [:show,:create,:update]

  def show
  ...
  end

  def create
  ...
  end

  def update
  ...
  end

  private
  def set_post
    @post = Post.find(params[:id])
  end
end

When a user is presented the opportunity to update a post for example the form would be generated for them, and on post, params[:id] would contain the ID of the appropiate post - probably owned by the current_user. 当向用户展示机会更新帖子时,例如将为他们生成表单,并且在帖子上,params [:id]将包含适当的帖子的ID(可能由current_user拥有)。

However, it would not be difficult for a malicious user to alter the posted :id variable to allow them to actually end up setting the @post variable in the controller, to represent a different post, rather than the original being updated. 但是,对于恶意用户而言,更改发布的:id变量以允许他们实际最终在控制器中设置@post变量(代表不同的帖子)而不是更新原始帖子并不困难。

I could see this being safer: 我可以看到这更安全:

private
def set_post
  @post = Post.find(params[:id])
  if(@post.user_id != current_user.id)
   redirect_to homepage, alert: "you can edit your own posts"
  end
end

However - that would stop other users viewing other people's posts! 但是,这将阻止其他用户查看其他人的帖子! So how and where should this kind of check be performed to ensure that only the owner of a particular post can update / edit it. 因此,应如何以及在何处执行这种检查,以确保只有特定帖子的所有者才能更新/编辑该帖子。 Is that something for the update controller action to handle itself with a check like this : 这是更新控制器操作通过如下检查来处理自身的事情:

def update
  if @post.user_id != current_user.id
    redirect_to homepage, alert: "you can edit your own posts"
  end
  ...
end

You are right, and I actually see that security issue being made very often by newbie Rails programmers. 没错,我实际上看到新手Rails程序员经常会遇到安全问题。 They just generate scaffolds and don't change things to their needs. 他们只是生成脚手架,不会改变其需求。

I'm using something like the following in my controllers: 我在控制器中使用了以下内容:

before_action :set_post
before_action :check_post_ownership, except: :show

private

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

def check_post_ownership
  redirect_to homepage, alert: "..." unless @post.user_id == current_user.id
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM