mcpField
L
laravel-policies-and-authorization

laravel-policies-and-authorization

github.com/noartem安全1378 次安装2 周前更新
代码仓库

关于 laravel-policies-and-authorization

面向 Laravel 开发者的授权实践技能,说明如何用 Policies 处理模型级操作、用 Gates 处理跨领域检查,并涵盖路由保护与测试。

主要功能

  1. 01按模型操作使用 Policy
  2. 02用 Gate 执行跨领域检查
  3. 03通过 can 中间件保护路由
  4. 04测试授权拒绝结果

适用场景

  1. 01为模型生成并配置 Policy
  2. 02保护资源控制器路由
  3. 03验证用户无权访问时的响应

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/noartem/skills --skill laravel-policies-and-authorization

安装后在 Claude Code 中输入/laravel-policies-and-authorization确认已加载。

详细介绍

策略与授权

对每个模型的操作使用策略;对跨领域检查使用门禁。

命令

# Generate a policy
sail artisan make:policy PostPolicy --model=Post   # or: php artisan make:policy PostPolicy --model=Post

# Apply in routes (resource controllers)
Route::resource('posts', PostController::class);
// In controller constructor
$this->authorizeResource(Post::class, 'post');

# One-off checks
$this->authorize('update', $post);           // in controller
Gate::allows('manage-billing', $user);       // ad-hoc gate

模式

  • 使用资源策略方法:viewAny, view, create, update, delete, restore, forceDelete
  • 优先使用策略方法,而非内联检查;这样可以保持控制器整洁
  • 在 AuthServiceProvider 中注册策略
  • 使用 can 中间件快速保护路由:->middleware('can:update,post')
  • 在测试中,对于拒绝的情况,断言 actingAs($user)->get(...)->assertForbidden()

评论

支持 Markdown