【问题标题】:Passing Data-ID Safely - Security Issue[Laravel]安全地传递 Data-ID - 安全问题[Laravel]
【发布时间】:2018-01-22 03:50:38
【问题描述】:

我有用户发布的帖子和一个打开模式的按钮,用户可以编辑帖子。

我目前有一个按钮,它有一个 data-id 并将 id 传递给模态,然后在模态中我设置更新 id 并在提交时提交。

这是一个问题,因为如果用户输入另一个 ID,例如 400,而不是可能是 50 的帖子 ID。

我怎样才能确保只更新该 ID/传递该 ID。

【问题讨论】:

    标签: javascript php jquery laravel laravel-5


    【解决方案1】:

    您需要将hidden input tag 用作post-id ,并且服务器端检查如果post 的user_id 等于登录用户的id 则只更新帖子。

    public function update(Request $request,$id){
        $post=Post::find($id);
        if($post){
            if($post->user_id == auth()->user()->id){
                 // update post
            }else{
                 // a person can not update post , redirect or show error        
            }
        }else{
            return view('error404');  // post not found,show 404 error page
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您使用Illuminate\Foundation\Http\FormRequest 进行验证,您可以使用authorize 方法。

      表单请求类还包含一个授权方法。这里面 方法,您可以检查经过身份验证的用户是否确实具有 更新给定资源的权限。

      假设你的路线是......

      Route::get('posts/edit/{post}', ['uses' => "PostController@update"]);
      

      然后在您的PostRequest 中,添加一个授权方法来验证用户正在编辑帖子。

      /**
       * Determine if the user is authorized to make this request.
       *
       * @return bool
       */
      public function authorize()
      {
          $post = Post::find($this->route('post'));
          return $post && $this->user()->can('update', $post);
      }
      

      如果您想自定义授权方法失败时的响应,您可以重写failedAuthorization()函数。

      /**
       * Handle a failed authorization attempt.
       *
       * @return void
       *
       * @throws \Illuminate\Auth\Access\AuthorizationException
       */
      protected function failedAuthorization()
      {
          // Spank user.
          throw new AuthorizationException('This action is unauthorized.');
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-24
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多