Laravel中是否需要为非帖子创建者的认证用户保护destroy删除方法
核心结论
- destroy方法必须添加同类权限防护,当前逻辑存在明显的越权操作漏洞。
- 已认证的非帖子创建者完全可以删除不属于自己的帖子。
非作者删除他人帖子的具体实现路径
你的__construct中配置的auth中间件仅会校验用户是否处于登录状态,不会校验登录用户和待操作资源的所属关系,且当前destroy方法内部没有任何权限校验逻辑:
- 假设你使用了Laravel默认的资源路由,删除操作对应DELETE请求,路径为
/posts/{post} - 攻击者登录后,只需要从公开的帖子列表页获取到任意他人帖子的ID,构造DELETE请求到
http://localhost/posts/目标帖子ID,即可直接触发destroy方法完成删除,不需要额外权限。
修复方案
方案1:直接在destroy方法中添加权限判断(逻辑和edit方法对齐)
修改后的destroy代码如下:
public function destroy(Post $post) { if (auth()->user()->id !== $post->user_id) { abort(403, 'Unauthorized.'); } Storage::disk('public')->delete($post->imagePath); $post->delete(); return redirect(route('posts.index'))->with('flash', 'Post Deleted Successfully'); }
方案2:使用Laravel权限策略(Policy)统一管理权限逻辑
如果后续还有update等需要校验所属关系的方法,推荐用策略避免重复写判断逻辑:
- 执行命令生成对应策略:
php artisan make:policy PostPolicy --model=Post - 在生成的
app/Policies/PostPolicy.php中添加删除权限判断:
public function delete(User $user, Post $post): bool { return $user->id === $post->user_id; }
- 在
app/Providers/AuthServiceProvider.php中完成策略注册 - 在destroy方法中调用校验即可:
$this->authorize('delete', $post);,无需再手动写判断逻辑。
内容的提问来源于stack exchange,提问作者Alphy Gacheru
相关产品推荐
相关产品推荐

