关于 laravel:policies-and-authorization
为 Laravel 开发提供策略与授权实践指南,适合需要组织模型级和跨领域访问控制的开发者。内容涵盖策略、Gate、中间件、控制器属性及拒绝访问测试。
主要功能
- 01按模型操作使用策略
- 02用 Gate 处理跨领域检查
- 03通过 can 中间件保护路由
- 04使用授权属性检查操作
- 05测试拒绝访问的响应
适用场景
- 01为资源控制器配置模型授权
- 02在路由中限制特定操作
- 03为 Laravel 13+ 控制器添加授权属性
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jpcaparas/ superpowers-laravel --skill laravel:policies-and-authorization安装后在 Claude Code 中输入/laravel:policies-and-authorization确认已加载。
详细介绍
策略与授权
针对单模型操作使用策略;针对横切检查使用 Gate。
命令
# 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()
Laravel 13+:授权属性
use Illuminate\Routing\Attributes\Controllers\Authorize;
use Illuminate\Routing\Attributes\Controllers\Middleware;
#[Middleware('auth')]
class CommentController
{
#[Authorize('create', [Comment::class, 'post'])]
public function store(Post $post) { /* ... */ }
#[Authorize('delete', 'comment')]
public function destroy(Comment $comment) { /* ... */ }
}
- 属性会在操作处明确显示策略检查;其效果等同于
$this->authorize(...)——在整个代码库中选择一种风格(参见laravel:php-attributes)
评论
支持 Markdown