【问题标题】:Laravel How to Validate Integrity of Model ID when SavedLaravel 如何在保存时验证模型 ID 的完整性
【发布时间】:2019-11-20 23:03:16
【问题描述】:

这可能有点偏执,但我想知道其他人如何确保在从前端编辑模型的 ID 时不会被欺骗。例如,查看以下基本形式:

<form id="form1" action="/profile/patch">
  @csrf
  <input type="hidden" name="id" value="{{ $profile.id }}">
  <input type="text" name="name" value="{{ $profile.name }}" placeholder="Your Name">
  <button>Submit</button>
</form>

有权管理多条记录的精明但恶意的人可以简单地进入他们的 Web 开发人员控制台并更改 ID 隐藏输入的值。这个例子有点基本,但我认为它可以用于更邪恶的方式。

我曾考虑通过在操作 URL 中包含 ID 来添加第二层验证:

<form id="form1" action="/profile/{{ $profile.id }}/patch">
  ...

...但这很容易被欺骗。

然后是javascript。即使是这样的东西也可以用控制台命令覆盖:

<script>
document.forms.form1.onsubmit = function() {
  // do some validation here
  document.forms.form1.elements['id'].value = {{ $profile.id }}; // dynamically insert the id
  return true;
}
</script>

似乎会话变量可能是唯一的方法,但这可能会很快变得混乱。我只是要忍受这个,还是我错过了什么?我是不是太偏执了?

【问题讨论】:

  • 你不能信任任何请求中的数据,你必须验证和处理授权......如果他们有多个事情的权限,那么他们就有这些事情的权限,那有什么好担心的
  • 我知道你来自哪里,你是对的,如果他们已经拥有权限,我可能会想太多,但你可以对 ID 进行的唯一验证是它存在或用户有权编辑该特定记录,而不是如果它与您开始使用的 ID 相同。我喜欢 KFoobar 加密 ID 的想法。

标签: laravel forms validation


【解决方案1】:

您可以加密 html 表单中的 ID 以防止用户修改它,甚至更好:根本不要在 html 表单中打印 ID(或其他敏感数据)并使用表单请求和验证(在 Laravel ) 以应用不需要与表单一起提交的 ID 和其他数据。 See documentation for Form Request here

例子:

public function rules()
{
    return [
        'user_id' => 'required|bail',
        'name' => 'required|string|bail',
    ];
}

protected function prepareForValidation()
{
    // This will add the user_id to the request after the form is submitted
    $this->merge([
        'user_id' => (auth()->check()) ? auth()->id() : null,
    ]);
}

如果您需要将 ID 与表单一起提交,您可以使用prepareForValidation() 来解密 ID:

protected function prepareForValidation()
{
    // This will decrypt the user id
    $this->merge([
        'user_id' => myDecryptFunction($this->input('hashed_user_id')),
    ]);
}

要在您的控制器中收集数据,请像这样注入您的表单请求:

public function store(MyFormRequest $request)
{
    $formDataAsArray = $request->validated();
}

【讨论】:

  • 我已经使用了表单请求和验证,我只是不明白在从前端重新提交表单时如何省略 ID?您的第一个示例适用于编辑自己的个人资料的用户,但不能编辑其他用户的个人资料。
猜你喜欢
  • 2016-09-25
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多