用户授权


1、简介

除了提供开箱即用的认证服务之外,Laravel 还提供了一个简单的方式来管理授权逻辑以便控制对资源的访问权限。和认证一样,在Laravel中实现授权很简单,主要有两种方式:gates和policies。

可以将gates和policies分别看作路由和控制器,gates提供了简单的基于闭包的方式进行授权,而policies和控制器一样,对特定模型或资源上的复杂授权逻辑进行分组,本着由简入繁的思路,我们首先来看gates,然后再看policies。

不要将gates和policies看作互斥的东西,实际上,在大多数应用中我们会混合使用它们,这很有必要,因为gates通常用于定于与模型或资源无关的权限,比如访问管理后台,与之相反,policies则用于对指定模型或资源的动作进行授权。

2、Gates

编写Gates

Gates是一个用于判断用户是否有权进行某项操作的闭包,通常使用Gate门面定义在App\Providers\AuthServiceProvider类中。Gates总是接收用户实例作为第一个参数,还可以接收相关的Eloquent模型实例作为额外参数:

/**
 * 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;
    });
}

授权动作

要使用gates授权某个动作,可以使用allows方法,需要注意的是你可以不传用户实例到allows方法,Laravel会自动将用户实例传递到gate闭包:

if (Gate::allows('update-post', $post)) {
    // The current user can update the post...
}

如果你想要判断指定用户(非当前用户)是否有权进行某项操作,可以使用Gate门面上的forUser方法:

if (Gate::forUser($user)->allows('update-post', $post)) {
    // The user can update the post...
}

3、创建策略类

生成Policies

Policies(策略)是用于组织基于特定模型或资源的授权逻辑的类,例如,如果你开发的是一个博客应用,可以有一个Post模型和与之对应的PostPolicy来授权用户创建或更新博客的动作。

我们使用Artisan命令make:policy来生成一个policy(策略),生成的policy位于app/Policies目录下,如果这个目录之前不存在,Laravel会为我们生成:

php artisan make:policy PostPolicy

make:policy命令会生成一个空的policy类,如果你想要生成一个包含基本CRUD策略方法的policy类,在执行该命令的时候可以通过--model指定相应模型:

php artisan make:policy PostPolicy --model=Post
注:所有策略类都通过服务容器进行解析,以便在策略类的构造函数中通过类型提示进行依赖注入。

注册Policies

Policies创建之后,需要进行注册。Laravel自带的AuthServiceProvider 包含了一个 policies 属性来映射Eloquent模型及与之对应的策略类。注册策略将会告知Laravel在授权给定模型动作时使用哪一个策略类:

<?php

namespace App\Providers;

use App\Post;
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

4、编写策略类

Policies方法

策略类被注册后,还要为每个授权动作添加方法,例如,我们为用户更新Post实例这一动作在PostPolicy中定义一个update方法。

update方法会接收一个User实例和一个Post实例作为参数,并且返回truefalse以表明该用户是否有权限对给定Post进行更新。因此,在这个例子中,我们验证用户的id和文章对应的user_id是否匹配:

<?php

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

你可以继续在策略类中为授权的权限定义更多需要的方法,例如,你可以定义 view或者 delete 等方法来授权多个 Post 动作,方法名不限。

注:如果你在使用Artisan命令生成策略类的时候使用了--model选项,那么策略类中已经包含了viewcreateupdatedelete动作。

不带模型的方法

有些策略方法只接收当前认证的用户,并不接收授权的模型实例作为参数,这种用法在授权create动作的时候很常见。例如,创建一篇博客的时候,你可能想要检查检查当前用户是否有权创建新博客。

当定义不接收模型实例的策略方法时,例如create方法,可以这么做:

/**
 * Determine if the given user can create posts.
 *
 * @param  \App\User  $user
 * @return bool
 */
public function create(User $user)
{
    //
}

策略过滤器

对特定用户,你可能想要在一个策略方法中对其授权所有权限,比如后台管理员。要实现这个功能,需要在策略类中定义一个before方法,before方法会在策略类的所有其他方法执行前执行,从而确保在其他策略方法调用前执行其中的逻辑:

public function before($user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}

5、使用策略授权动作

通过User模型

Laravel自带的 User 模型提供了两个方法用于授权动作: cancantcan 方法接收你想要授权的动作和对应的模型作为参数。例如,下面的例子我们判断用户是否被授权更新给定的Post模型:

if ($user->can('update', $post)) {
    //
}

如果给定模型对应的策略已经注册,则 can 方法会自动调用相应的策略并返回布尔结果。如果给定模型没有任何策略被注册, can 方法将会尝试调用与动作名称相匹配的Gate闭包。

不依赖于模型的动作

有些动作比如 create 并不需要依赖给定模型实例,在这些场景中,可以传递一个类名到 can 方法,这个类名会在进行授权的时候用于判断使用哪一个策略:

use App\Post;

if ($user->can('create', Post::class)) {
    // Executes the "create" method on the relevant policy...
}

通过中间件

Laravel提供了一个可以在请求到达路由或控制器之前进行授权的中间件—— Illuminate\Auth\Middleware\Authorize ,默认情况下,这个中间件在 App\Http\Kernel 类中被分配了一个can别名,下面我们来探究如何使用can中间件授权用户更新博客文章动作:

use App\Post;

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

在这个例子中,我们传递了两个参数给 can 中间件,第一个是我们想要授权的动作名称,第二个是我们想要传递给策略方法的路由参数。在这个例子中,由于我们使用了隐式模型绑定, Post 模型将会被传递给策略方法,如果没有对用户进行给定动作的授权,中间件将会生成并返回一个状态码为403的HTTP响应。

不依赖于模型的动作

同样,对那些不需要传入模型实例的动作如create,需要传递类名到中间件,类名将会在授权动作的时候用于判断使用哪个策略:

Route::post('/post', function () {
    // The current user may create posts...
})->middleware('can:create,App\Post');

通过控制器辅助函数

除了提供给User模型的辅助函数,Laravel还为继承自 App\Http\Controllers\Controller 基类的所有控制器提供了 authorize 方法,和can方法类似,该方法接收你想要授权的动作名称以及相应模型实例作为参数,如果动作没有被授权, authorize 方法将会抛出 Illuminate\Auth\Access\AuthorizationException ,Laravel默认异常处理器将会将其转化为状态码为403的HTTP响应:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * Update the given blog post.
     *
     * @param  Request  $request
     * @param  Post  $post
     * @return Response
     */
    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // The current user can update the blog post...
    }
}

不依赖模型的动作

和之前讨论的一样,类似 create 这样的动作不需要传入模型实例参数,在这些场景中,可以传递类名给 authorize 方法,该类名将会在授权动作时判断使用哪个策略:

/**
 * Create a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function create(Request $request)
{
    $this->authorize('create', Post::class);

    // The current user can create blog posts...
}

通过Blade模板

编写Blade模板的时候,你可能想要在用户被授权特定动作的情况下才显示对应的视图模板部分,例如,你可能想要在用户被授权更新权限的情况下才显示更新表单。在这种情况下,你可以使用 @can@cannot 指令:

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@endcan

@cannot('update', $post)
    <!-- The Current User Can't Update The Post -->
@endcannot

这种写法可看作是@if@unless语句的缩写,上面的  @can@cannot 语句与下面的语句等价:

@if (Auth::user()->can('update', $post))
    <!-- The Current User Can Update The Post -->
@endif

@unless (Auth::user()->can('update', $post))
    <!-- The Current User Can't Update The Post -->
@endunless

不依赖模型的动作

和其它授权方法一样,如果授权动作不需要传入模型实例的情况下可以传递类名给 @can@cannot 指令:

@can('create', Post::class)
    
@endcan

@cannot('create', Post::class)
    
@endcannot

点赞 取消点赞 收藏 取消收藏

<< 上一篇: API认证(Passport)

>> 下一篇: 密码重置