介绍

除了开箱即用地提供身份验证服务外,Lumen还提供了一种简单的方法来组织授权逻辑并控制对资源的访问。有多种方法和助手可以帮助您组织授权逻辑。
通常,可以在Lumen中使用授权,就像在Laravel中使用授权一样。我们将在此处介绍一些差异,但是您应该参考Laravel完整文档以获取更多详细信息。

与Laravel的区别

定义能力

与Laravel相比,在Lumen中使用授权的主要区别在于如何定义功能。在流明中,您可以仅使用Gate外墙AuthServiceProvider来定义能力:

  1. Gate::define('update-post', function ($user, $post) {
  2. return $user->id === $post->user_id;
  3. });

定义政策

与Laravel不同,Lumen的$policies数组没有AuthServiceProvider。但是,您仍然可以从提供者的方法中policyGate外观上调用该boot方法:

  1. Gate::policy(Post::class, PostPolicy::class);

同样,要了解有关策略的更多信息,请查阅完整的Laravel文档

检查能力

您可以像在整个Laravel框架中一样“检查”功能。首先,您可以使用Gate立面。如果选择使用外观,请确保在文件中启用外观。请记住,我们不需要将实例传递到方法中,因为当前已通过身份验证的用户将自动传递到您的授权回调:bootstrap/app.php``User``allows

  1. if (Gate::allows('update-post', $post)) {
  2. //
  3. }
  4. if (Gate::denies('update-post', $post)) {
  5. abort(403);
  6. }

当然,您也可以检查给定User实例是否具有给定功能:

  1. if ($request->user()->can('update-post', $post)) {
  2. // The user is allowed to update the post...
  3. }
  4. if ($request->user()->cannot('update-post', $post)) {
  5. abort(403);
  6. }