Gates and strategies in Laravel

WBOY
Release: 2023-08-31 13:50:01
Original
1498 people have browsed it

Gates and strategies in Laravel

Today, we will discuss the authorization system of Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After introducing gates and strategies, I'll demonstrate the concepts by implementing a custom example.

I assume you already know about the built-in Laravel authentication system, as this is required to understand the authorization concept. Obviously, the authorization system works together with the authentication system to identify legitimate user sessions.

If you don't know about the Laravel authentication system, I highly recommend reading the official documentation, which will give you an in-depth understanding of the topic.

Laravel’s authorization method

By now, you should know that the Laravel authorization system comes in two flavors: gates and policies. While this may sound like a complicated thing, I would say that once you get the hang of it, it's pretty easy to do!

Gate allows you to define authorization rules using a simple closure-based approach. In other words, when you want to authorize operations that are not tied to any particular model, gates are the perfect place to implement that logic.

Let’s take a quick look at what gate-based authorization looks like:

...
...
Gate::define('update-post', function ($user, $post) {
  return $user->id == $post->user_id;
});
...
...
Copy after login

The code snippet above defines the authorization rules update-post You can call this from anywhere in your application.

On the other hand, you should use strategies when you want to group authorization logic for any model. For example, suppose you have a Post model in your application, and you want to authorize CRUD operations on that model. In this case, this is the strategy you need to implement.

class PostPolicy
{
  public function view(User $user, Post $post) {}
  public function create(User $user) {}
  public function update(User $user, Post $post) {}
  public function delete(User $user, Post $post) {}
}
Copy after login

As you can see, this is a very simple policy class that defines authorization for CRUD operations on the Post model.

This is an introduction to gates and strategies in Laravel. Starting in the next section, we'll give a practical demonstration of each element.

door

In this section, we will understand the concept of doors through a real-life example.

How to create a custom door

When you need to register a component or service, you'll typically look for a Laravel service provider. Following that convention, let's go ahead and define the custom gate in app/Providers/AuthServiceProvider.php as shown in the following code snippet.

<?php
namespace App\Providers;
 
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
 
class AuthServiceProvider extends ServiceProvider
{
  /**
   * The policy mappings for the application.
   *
   * @var array
   */
  protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
  ];
 
  /**
   * Register any authentication / authorization services.
   *
   * @return void
   */
  public function boot()
  {
    $this->registerPolicies();
     
    Gate::define('update-post', function ($user, $post) {
      return $user->id == $post->user_id;
    });
  }
}
Copy after login

In the boot method, we define the custom door:

Gate::define('update-post', function ($user, $post) {
  return $user->id == $post->user_id;
});
Copy after login

When a gate is defined, it requires a closure that returns TRUE or FALSE depending on the authorization logic defined in the gate definition. There are other ways to define gates besides closure functions.

For example, the following gate definition calls a controller action instead of a closure function.

Gate::define('update-post', 'ControllerName@MethodName');
Copy after login

How to use our custom gates

Now, let's go ahead and add a custom route so that we can demonstrate how gate-based authorization works. In the routes file routes/web.php, add the following routes.

Route::get('service/post/gate', 'PostController@gate');
Copy after login

Let’s also create an associated controller file app/Http/Controllers/PostController.php.

<?php
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Support\Facades\Gate;
 
class PostController extends Controller
{
  /* Make sure you don't use Gate and Policy altogether for the same Model/Resource */
  public function gate()
  {
    $post = Post::find(1);
 
    if (Gate::allows('update-post', $post)) {
      echo 'Allowed';
    } else {
      echo 'Not Allowed';
    }
     
    exit;
  }
}
Copy after login

In most cases, you will end up using the allows or denies methods (Gate facades) to authorize specific actions. In the above example, we use the allows method to check if the current user is able to perform the update-post operation.

Eagle-eyed users will notice that we only pass the second parameter $post to the closure. The first parameter is the currently logged in user, which is automatically injected by the Gate facade.

This is how you should use gates to authorize actions in your Laravel application. If you wish to implement authorization for your model, the next section explains how to use policies.

policy

As we discussed before, when you want to logically group authorization operations for any specific model or resource, what you need is a policy.

How to create a custom policy

In this section we will create a policy for the Post model that authorizes all CRUD operations. I'm assuming you've already implemented the Post model in your application; otherwise, something similar will do.

Laravel artisan Commands are your best friends when creating stub code. You can use the following artisan command to create a strategy for the Post model.

$php artisan make:policy PostPolicy --model=Post
Copy after login

As you can see, we provide the --model=Post parameter so that it creates all CRUD methods. If not, it creates a blank policy class. You can find the newly created policy class in app/Policies/PostPolicy.php.

<?php

namespace App\Policies;

use App\Post;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        //
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can restore the model.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function restore(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can permanently delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function forceDelete(User $user, Post $post)
    {
        //
    }
}
Copy after login

Let’s replace it with the following code.

<?php
namespace App\Policies;
 
use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
 
class PostPolicy
{
  use HandlesAuthorization;
 
  /**
   * Determine whether the user can view the post.
   *
   * @param  \App\User  $user
   * @param  \App\Post  $post
   * @return mixed
   */
  public function view(User $user, Post $post)
  {
    return TRUE;
  }
 
  /**
   * Determine whether the user can create posts.
   *
   * @param  \App\User  $user
   * @return mixed
   */
  public function create(User $user)
  {
    return $user->id > 0;
  }
 
  /**
   * Determine whether the user can update the post.
   *
   * @param  \App\User  $user
   * @param  \App\Post  $post
   * @return mixed
   */
  public function update(User $user, Post $post)
  {
    return $user->id == $post->user_id;
  }
 
  /**
   * Determine whether the user can delete the post.
   *
   * @param  \App\User  $user
   * @param  \App\Post  $post
   * @return mixed
   */
  public function delete(User $user, Post $post)
  {
    return $user->id == $post->user_id;
  }
}
Copy after login

In order to be able to use our strategy class, we need to register it with the Laravel service provider, as shown in the following code snippet.

<?php
namespace App\Providers;
 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use App\Post;
use App\Policies\PostPolicy;
 
class AuthServiceProvider extends ServiceProvider
{
  /**
   * The policy mappings for the application.
   *
   * @var array
   */
  protected $policies = [
    Post::class => PostPolicy::class
  ];
 
  /**
   * Register any authentication / authorization services.
   *
   * @return void
   */
  public function boot()
  {
    $this->registerPolicies();
  }
}
Copy after login

We have added policy mapping in the $policies attribute. It tells Laravel to call the appropriate policy method to authorize CRUD operations.

您还需要使用 registerPolicies 方法注册策略,就像我们在 boot 方法中所做的那样。

没有模型的策略方法

PostPolicy 策略类中的 create 方法仅采用单个参数,这与采用两个参数的其他模型方法不同。一般来说,第二个参数是模型对象,您将在执行授权时使用它。但是,在 create 方法的情况下,您只需要检查是否允许相关用户创建新帖子。

在下一节中,我们将了解如何使用自定义策略类。

如何使用我们的自定义策略类

更进一步,让我们在 routes/web.php 文件中创建几个自定义路由,以便我们可以在那里测试我们的策略方法。

Route::get('service/post/view', 'PostController@view');
Route::get('service/post/create', 'PostController@create');
Route::get('service/post/update', 'PostController@update');
Route::get('service/post/delete', 'PostController@delete');
Copy after login

最后,让我们在 app/Http/Controllers/PostController.php 创建一个关联的控制器。

<?php
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Support\Facades\Auth;
 
class PostController extends Controller
{
  public function view()
  {
    // get current logged in user
    $user = Auth::user();
     
    // load post
    $post = Post::find(1);
     
    if ($user->can('view', $post)) {
      echo "Current logged in user is allowed to update the Post: {$post->id}";
    } else {
      echo 'Not Authorized.';
    }
  }
 
  public function create()
  {
    // get current logged in user
    $user = Auth::user();
 
    if ($user->can('create', Post::class)) {
      echo 'Current logged in user is allowed to create new posts.';
    } else {
      echo 'Not Authorized';
    }
 
    exit;
  }
 
  public function update()
  {
    // get current logged in user
    $user = Auth::user();
 
    // load post
    $post = Post::find(1);
 
    if ($user->can('update', $post)) {
      echo "Current logged in user is allowed to update the Post: {$post->id}";
    } else {
      echo 'Not Authorized.';
    }
  }
 
  public function delete()
  {
    // get current logged in user
    $user = Auth::user();
     
    // load post
    $post = Post::find(1);
     
    if ($user->can('delete', $post)) {
      echo "Current logged in user is allowed to delete the Post: {$post->id}";
    } else {
      echo 'Not Authorized.';
    }
  }
}
Copy after login

您可以通过不同的方式使用策略来授权您的操作。在上面的示例中,我们使用 User 模型来授权我们的 Post 模型操作。

User 模型提供了两种有用的授权方法 — cancantcan 方法用于检查当前用户是否能够执行某个操作。而与 can 方法对应的 cant 方法,用于判断动作是否无法执行。

让我们从控制器中获取 view 方法的片段,看看它到底做了什么。

public function view()
{
  // get current logged in user
  $user = Auth::user();
   
  // load post
  $post = Post::find(1);
   
  if ($user->can('view', $post)) {
    echo "Current logged in user is allowed to update the Post: {$post->id}";
  } else {
    echo 'Not Authorized.';
  }
}
Copy after login

首先,我们加载当前登录的用户,这为我们提供了 User 模型的对象。接下来,我们使用 Post 模型加载示例帖子。

接下来,我们使用 User 模型的 can 方法来授权 Post 模型的 view 操作。 can 方法的第一个参数是您要授权的操作名称,第二个参数是您要授权的模型对象。

这是如何使用 User 模型通过策略授权操作的演示。或者,如果您在控制器中授权某个操作,则也可以使用控制器助手。

…
$this->authorize('view', $post);
…
Copy after login

如您所见,如果您使用控制器助手,则无需加载 User 模型。

如何通过中间件使用策略

或者,Laravel 还允许您使用中间件授权操作。让我们快速查看以下代码片段,了解如何使用中间件来授权模型操作。

Route::put('/post/{post}', function (Post $post) {
    // Currently logged-in user is allowed to update this post.... 
})->middleware('can:update,post');
Copy after login

在上面的示例中,它将使用 can 中间件。我们传递两个参数:第一个参数是我们想要授权的操作,第二个参数是路由参数。根据隐式模型绑定的规则,第二个参数会自动转换为 Post 模型对象,并作为第二个参数传递。如果当前登录的用户无权执行 update 操作,Laravel 将返回 403 状态代码错误。

如何将策略与刀片模板结合使用

如果您希望在登录用户被授权执行特定操作时显示代码片段,您还可以在刀片模板中使用策略。让我们快速看看它是如何工作的。

@can('delete', $post)
    <!-- Display delete link here... -->
@endcan
Copy after login

在上述情况下,它只会向有权对 Post 模型执行删除操作的用户显示删除链接。

这就是您可以使用的策略概念,在授权模型或资源时它非常方便,因为它允许您将授权逻辑分组在一个地方。

只需确保您不会将门和策略一起用于模型的相同操作,否则会产生问题。这就是我今天的内容,今天就到此为止!

结论

今天,Laravel 授权占据了我文章的中心位置。在文章的开头,我介绍了 Laravel 授权、网关和策略的主要要素。

接下来,我们创建了自定义门和策略,以了解它在现实世界中的工作原理。我希望您喜欢这篇文章,并在 Laravel 环境中学到了一些有用的东西。

对于刚刚开始使用 Laravel 或希望通过扩展来扩展您的知识、网站或应用程序的人,我们在 Envato Market 上提供了多种可供您学习的内容。

The above is the detailed content of Gates and strategies in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!