Gra*_*yda 32

我也想知道这个问题,经过一番阅读后,我得出的结论是:

中间件

通常在路由上运行(但您也可以在控制器方法上运行它),并且可用于过滤或检查传入请求

一个例子是auth,它确定尝试请求特定路由的人是否已通过系统身份验证(登录)。另一个示例是检查请求是否具有特定标头(例如,如果您想检查应用程序是否正在发送X-MYAPP-CUSTOMHEADER或其他内容)

如前所述,中间件可以在路由上(例如在web.php或 中api.php)或在控制器中定义。

web.php 中的示例:

// Get all the posts, but only if the user has signed in to the website 
Route::get('/posts', [PostController::class, 'index'])->middleware('auth');
Run Code Online (Sandbox Code Playgroud)

中的一个例子PostController.php

public function __construct() {
    // Apply the `auth` middleware to every function in this controller
    $this->middleware('auth');
    // Apply the `signed` middleware, but only to the functions `download` and `delete`
    $this->middleware('signed', ['only' => ['download', 'delete']]);
}

Run Code Online (Sandbox Code Playgroud)

盖茨

AuthServiceProvider.php门是在文件(App\Providers文件夹中)中定义的函数,指定允许用户执行的操作和不允许执行的操作。例如:

Gate::define('delete-post', function (User $user, Post $post) {
    return $user->id === $post->user_id;
});
Run Code Online (Sandbox Code Playgroud)

然后在你的PostController方法中delete

public function delete(Request $request, Post $post)
{
    if (Gate::denies('delete-post', $post)) { // Returns true if `$post->user_id` is not the same as `$user->id` (a.k.a the user is not allowed to delete this post)
        abort(403);
    }

    $post->delete();
}
Run Code Online (Sandbox Code Playgroud)

您还可以在刀片模板中使用一些辅助方法:

@can('delete-post', $post)
    <!-- Show a link to the delete page here -->
@endcan
Run Code Online (Sandbox Code Playgroud)

(我在下面对此进行了扩展)

卫兵

防护是一种指定如何针对请求对用户进行身份验证的方法。

在我正在从事的一个项目中,jwt我的 API 路由上有一个(JSON Web 令牌)保护。这意味着当我执行类似的操作时auth()->attempt(['username' => 'test', 'password' => 'test']);,该auth()函数将尝试使用jwt守卫对我进行身份验证。

使用哪个防护在 中指定auth.php。我的目前看起来像这样:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users'
        ],
    ],
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,通过浏览器传入的请求将在登录时分配一个会话,而通过 API 调用传入的请求将需要获取/提供令牌进行身份验证。验证时两者都会查表users检查用户名/密码。

您可以指定调用时使用哪个守卫auth()

auth('api')->attempt(['api_key' => 'abc1234'])

(旁注,我遇到了这个问题,因为我想知道为什么auth()->user()不返回当前用户,那是因为web这是默认的防护,我试图获取通过身份验证的用户api,所以一定要明确哪个守卫!)

政策

策略的工作方式与门类似,但仅适用于特定模型并存储在自己的文件中(在App\Policies

您可以使用 来创建一个php artisan make:policy PostPolicy -m Post。它将创建一个名为 的文件,PostPolicy.php该文件将创建一堆函数:

viewAny // Can the user even look at this model? If no, they'll be denied for all the below methods
view // Can the user look at the specified Post?
create // Can they create a new Post
update // Can they edit / update the specified Post?
delete // Can they (soft) delete the specified Post?
restore // Can they restore the specified (soft) deleted Post?
forceDelete // Can they force delete the specified Post?
Run Code Online (Sandbox Code Playgroud)

典型的函数如下所示:

public function viewAny(User $user)
{
    // If this returns true, then the other methods will be evaluated.
    return $user->can_view_posts;
}

public function forceDelete(User $user, Post $post)
{
    // If this returns true, then the user can force delete the post.
    // This depends on viewAny being true
    return $post->user_id == $user->id;
}
Run Code Online (Sandbox Code Playgroud)

需要注意的一件事是,这viewAny与“查看全部”不同!可以将其视为viewAny建筑物的前门。如果viewAny为 true,您可以进入大厅,但您无法查看任何房间的内部,除非view特定房间也为 true。

我相信您还可以将@can刀片模板与策略一起使用:

@can('forceDelete', $post)
    <!-- Show button to force delete a post here -->
@endcan
Run Code Online (Sandbox Code Playgroud)

反之亦然:

@cannot('view', $post)
    <!-- Show a greyed out button or something -->
@cannot
Run Code Online (Sandbox Code Playgroud)

以及@canany用于检查多个权限:

@canany(['edit', 'delete'])
    <!-- Show something if the user can edit OR delete -->
@endcanany
Run Code Online (Sandbox Code Playgroud)

结论

我希望这有用。在阅读本文时我确实学到了很多东西。这比我想象的要多得多,所以值得查看 Laravel 文档,因为我在某些方面可能是正确的,但在其他方面可能是错误的。