安全传递数据 ID - 安全问题[Laravel].



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

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

这是一个问题,因为如果用户输入另一个 id 400而不是该帖子 id 可能会50

我怎么能确保只更新该 id/传递该 id。

您需要为post-id取hidden input tag,服务器端检查如果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
    }
}

如果使用IlluminateFoundationHttpFormRequest执行验证,则可以使用 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 IlluminateAuthAccessAuthorizationException
 */
protected function failedAuthorization()
{
    // Spank user.
    throw new AuthorizationException('This action is unauthorized.');
}

最新更新