Laravel 用户授权 Gate和Policy

简介: 要点:Laravel 有 2 种主要方式来实现用户授权:gates 和策略。Gates 接受一个当前登录用户的实例作为第一个参数。并且接收可选参数,比如相关的Eloquent 模型。

要点:

  • Laravel 有 2 种主要方式来实现用户授权:gates 和策略。
  • Gates 接受一个当前登录用户的实例作为第一个参数。并且接收可选参数,比如相关的Eloquent 模型。
  • 用命令生成策略 php artisan make:policy PostPolicy --model=Post
    --model参数生成的内容包含CRUD方法
  • Gate用在模型和资源无关的地方,Policy正好相反。
<?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)
    {
        //
    }

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

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

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

操作流程:

  1. 新建Post表及Model文件
    php artisan make:migrate create_posts_table
    php artisan make:model Post
    表信息
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->integer('user_id')->unsigned();
            $table->text('body');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

填充数据,打开UserFactory添加

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
        'body' => $faker->paragraph,
        'user_id' => factory(\App\User::class)->create()->id,
    ];
});

Post表内容


img_ee0038ac774e61f6810d2fe9e3dc9ad0.png
image.png
  1. routes/web.php添加
    Route::resource('posts', 'PostsController');

  2. 定义Gate
    打开 Proviers/AuthServiceProvider.php,修改boot方法

    public function boot()
    {
        $this->registerPolicies();

        // Gates 接受一个用户实例作为第一个参数,并且可以接受可选参数,比如 相关的 Eloquent 模型:
        Gate::define('update-post', function ($user, $post) {
            // return $user->id == $post->user_id;
            return $user->owns($post);
        });
    }

这里,在User模型中定义了own方法

    public function owns($post)
    {
        return $post->user_id === $this->id;
    }
  1. PostsController中,只写一个show方法
    // Gate 演示
    public function show($id)
    {
        $post = Post::findOrFail($id);

        \Auth::loginUsingId(2);

        $this->authorize('update-post', $post);

        if (Gate::denies('update-post', $post)) {
            abort(403, 'sorry');
        }


        // compact('post') 等价于 ['post' => $post]
        return view('posts.view', compact('post'));
        // return $post->title;
    }
  1. 访问 /posts/1。会报403。这是因为我们是用user_id为2登录。
img_3c484e60450bed8a690c2347dceadebc.png
image.png
  1. 如果注释 $this->authorize('update-post', $post);,就会显示:

    img_54ae112678138679da8aed122b1248d9.png
    image.png

  2. 视图中判断Policy,如果post的user_id是当前登录用户,显示编辑链接。

@can('update', $post)
<a href="#">编辑</a>
@endcan

@can 和 @cannot 各自转化为如下声明:

@if (Auth::user()->can('update', $post))
    <!-- 当前用户可以更新博客 -->
@endif

@unless (Auth::user()->can('update', $post))
    <!-- 当前用户不可以更新博客 -->
@endunless

参考:https://d.laravel-china.org/docs/5.5/authorization

相关文章
|
6月前
|
安全
Spartacus Storefront 里如何在 SmartEdit 访问环境下暂时禁用 Early login
Spartacus Storefront 里如何在 SmartEdit 访问环境下暂时禁用 Early login
33 0
|
安全 jenkins 持续交付
Jenkins常用插件介绍之权限控制插件Role-based Authorization Strategy
除了搭建jenkins时默认安装的插件之外,有时候扩展功能,还需要安装一些其他的插件,下面为大家简单介绍一下Role-based Authorization Strategy插件。
Jenkins常用插件介绍之权限控制插件Role-based Authorization Strategy
|
jenkins 持续交付 数据安全/隐私保护
『Jenkins』Jenkins实现权限控制——Role-based Authorization Strategy
📣读完这篇文章里你能收获到 - 本文将以图文的形式带你一步一步配置Jenkins角色权限 - 你将了解到角色权限的概念及账号的管理
186 0
『Jenkins』Jenkins实现权限控制——Role-based Authorization Strategy
|
JavaScript 前端开发 安全
关于 SAP Spartacus OAuth 2.0 Resource Owner Password Flow 实现的一些讨论
关于 SAP Spartacus OAuth 2.0 Resource Owner Password Flow 实现的一些讨论
419 0
基于SAML2.0的SAP云产品Identity Authentication过程介绍
SAP官网的架构图https://cloudplatform.sap.com/scenarios/usecases/authentication.html 上图介绍了用户访问SAP云平台时经历的Authentication过程。
921 0
|
JavaScript 对象存储 数据安全/隐私保护
还在写RAM policy授权脚本?试试通过Bucket Policy一键配置细颗粒度访问权限
一、阿里云提供完善且全面的权限管控体系     阿里云提供业内最为完善的权限管控体系,涵盖了“基于资源的权限管理”以及“基于用户的权限管理”层面。并且阿里云“访问控制”采用基于ABAC(Attribute Based Access Control)而不是简单的RBAC(Role Based Access Control),用户可以访问者的当前环境属性(例如,current time、source ip、HTTP访问方式、prefix等参数)判断是否具有相应的操作权限。
|
PHP 数据安全/隐私保护
Laravel中自定义guard,自定义Auth的attempt方法
这个今天算是踩到坑了。 将普通用户和管理员用户分别放在不同的表里。 那么,前台和后台登陆时, 认证的东东就要分开。 开始还顺利, 等认证完成之后, 却无法获取登陆的用户。
6557 0