mcpField
L
laravel-authorization-patterns

laravel-authorization-patterns

github.com/iserter安全4893 次安装27 周前更新
代码仓库

关于 laravel-authorization-patterns

面向 Laravel 开发者的授权模式参考技能,涵盖 Gate、Policy 及框架授权入口。可用于在路由、控制器、请求和视图中统一实施访问检查。

主要功能

  1. 01使用 Gate 检查通用能力
  2. 02使用 Policy 处理模型授权
  3. 03返回详细授权响应
  4. 04在中间件和控制器中授权
  5. 05使用 Blade 授权指令
  6. 06编写授权测试

适用场景

  1. 01定义与模型无关的能力
  2. 02用策略保护模型操作
  3. 03为路由和表单请求添加检查
  4. 04测试允许与拒绝的访问

安装

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

$npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-authorization-patterns

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

详细介绍

Laravel 授权模式

用于通用能力检查的 Gate

// In AuthServiceProvider or AppServiceProvider boot()
use Illuminate\Support\Facades\Gate;

Gate::define('access-admin', function (User $user) {
    return $user->is_admin;
});

Gate::define('manage-settings', function (User $user) {
    return $user->hasRole('admin');
});

// Usage
if (Gate::allows('access-admin')) {
    // ...
}

// ✅ Abort if unauthorized
Gate::authorize('access-admin'); // Throws AuthorizationException

// ✅ Check for specific user
Gate::forUser($otherUser)->allows('access-admin');

基于模型的授权策略

<?php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class PostPolicy
{
    // Runs before all other checks - return null to fall through
    public function before(User $user, string $ability): ?bool
    {
        if ($user->is_super_admin) {
            return true;
        }

        return null; // Fall through to specific method
    }

    public function viewAny(User $user): bool
    {
        return true;
    }

    public function view(User $user, Post $post): bool
    {
        return $post->is_published || $user->id === $post->user_id;
    }

    public function create(User $user): bool
    {
        return $user->hasVerifiedEmail();
    }

    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): Response
    {
        if ($user->id !== $post->user_id) {
            return Response::deny('You do not own this post.');
        }

        if ($post->is_published) {
            return Response::denyWithStatus(403, 'Published posts cannot be deleted.');
        }

        return Response::allow();
    }
}

当策略遵循 App\Policies\{Model}Policy 约定时,系统会自动发现这些策略。

响应对象

use Illuminate\Auth\Access\Response;

// ✅ Rich authorization responses
public function publish(User $user, Post $post): Response
{
    if (! $user->hasVerifiedEmail()) {
        return Response::denyWithStatus(403, 'Verify your email first.');
    }

    if ($post->user_id !== $user->id) {
        return Response::denyAsNotFound(); // Returns 404 instead of 403
    }

    return Response::allow();
}

// Inspecting responses without exceptions
$response = Gate::inspect('publish', $post);

if ($response->allowed()) {
    // Publish the post
} else {
    echo $response->message();
}

中间件授权

// ✅ Route-level authorization
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->can('update', 'post');

Route::resource('posts', PostController::class)
    ->middleware('can:viewAny,App\Models\Post')
    ->only(['index']);

// ✅ Route group with gate
Route::middleware('can:access-admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'index']);
    Route::get('/admin/users', [AdminController::class, 'users']);
});

Blade 指令

{{-- ✅ Single ability check --}}
@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

{{-- ✅ Multiple abilities --}}
@canany(['update', 'delete'], $post)
    <div class="actions">
        @can('update', $post)
            <button>Edit</button>
        @endcan
        @can('delete', $post)
            <button>Delete</button>
        @endcan
    </div>
@endcanany

{{-- ✅ Inverse check --}}
@cannot('create', App\Models\Post::class)
    <p>You do not have permission to create posts.</p>
@endcannot

{{-- ✅ Gate check --}}
@can('access-admin')
    <a href="/admin">Admin Panel</a>
@endcan

Form Request 的 authorize() 集成

class UpdatePostRequest extends FormRequest
{
    // ✅ Combine validation with authorization
    public function authorize(): bool
    {
        return $this->user()->can('update', $this->route('post'));
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'content' => ['required', 'string'],
        ];
    }
}

控制器授权

class PostController extends Controller
{
    public function index()
    {
        // ✅ Authorize against model class
        $this->authorize('viewAny', Post::class);

        return Post::paginate();
    }

    public function update(UpdatePostRequest $request, Post $post)
    {
        // ✅ Authorize against model instance
        $this->authorize('update', $post);

        $post->update($request->validated());

        return new PostResource($post);
    }

    // ❌ Don't check authorization with manual if statements
    public function destroy(Post $post)
    {
        if (auth()->id() !== $post->user_id) {
            abort(403);
        }
        // Skips policy, no reuse, harder to test
    }

    // ✅ Use policy
    public function destroy(Post $post)
    {
        $this->authorize('delete', $post);

        $post->delete();

        return response()->noContent();
    }
}

测试授权

use Illuminate\Support\Facades\Gate;

// ✅ Test policy methods directly
public function test_user_can_update_own_post(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->for($user)->create();

    $this->assertTrue($user->can('update', $post));
}

public function test_user_cannot_update_others_post(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->create(); // Different user

    $this->assertFalse($user->can('update', $post));
}

// ✅ Test via HTTP
public function test_unauthorized_user_gets_403(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->create();

    $this->actingAs($user)
        ->putJson("/api/posts/{$post->id}", ['title' => 'New Title'])
        ->assertForbidden();
}

// ✅ Bypass authorization in other tests
public function test_post_update_logic(): void
{
    Gate::before(fn () => true); // Allow everything

    // Test business logic without auth concerns
}

检查清单

  • 使用 Gate 处理与模型无关的通用能力
  • 使用策略处理所有基于模型的授权
  • 策略遵循自动发现命名约定
  • before() 返回 null 以继续执行(而不是 false)
  • 使用响应对象提供详细的拒绝消息
  • 通过中间件、Form Request 或控制器应用授权
  • 使用 Blade 指令有条件地渲染 UI
  • 不使用绕过策略的手动 if/abort(403) 检查
  • 测试授权逻辑的允许和拒绝情况
  • 需要响应消息时使用 Gate::inspect()

评论

支持 Markdown