laravel策略(this action is unauthorized)

授权用户是否可以执行某个动作

方法1:

可以通过编写Gates进行定义

在App\Providers\AuthServiceProvider文件中的boot方法中:

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

        Gate::define('userupdate', function ($currentUser,$model) {
            return $currentUser->id === $model->id;
        });

    }

  $currentUser是当前登录用户,$model是要操作的模型,通过判断当前用户模型以及要操作的模型的id是否相等,来授权用户是否能进行某一步的操作

控制器使用

$bool = Gate::allows('userupdate', $user);//如果两者的id相等$bool为true,否则为false,如果使用Gate::authorize('update', $post);没有权限时抛出异常,http响应报错
具体其它的操作方法可以在laravel文档中查看https://learnku.com/docs/laravel/6.x/authorization/5153
 
方法二:
创建策略
生成策略
php artisan make:policy PostPolicy        //生成的策略将放在 app/Policies 目录
生成策略后就要注册:
注册一个策略将指导 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
{
    /**
     * 应用程序的策略映射。
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,//post模型对应post策略
    ];

    /**
     * 注册任何应用程序 authentication / authorization 服务。
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

  也可以使用自动注册策略:

<?php

namespace App\Providers;
.
.
.
class AuthServiceProvider extends ServiceProvider
{
    .
    .
    .
    public function boot()
    {
        $this->registerPolicies();
        // 修改策略自动发现的逻辑
        Gate::guessPolicyNamesUsing(function ($modelClass) {
            // 动态返回模型对应的策略名称,如:// 'App\Models\User' => 'App\Policies\UserPolicy',
            return 'App\Policies\\'.class_basename($modelClass).'Policy';
        });
    }
}
//这里的模型都是放在App\Models\目录

  编写策略:

<?php

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * 确定用户是否可以更新给定的帖子。
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

  控制器使用策略:

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * 更新指定博客帖子。
     *
     * @param  Request  $request
     * @param  Post  $post
     * @return Response
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);//也可以使用Gate::authorize('update', $post);
      //如果使用以上两个都报错this action is unauthorized,那就使用方法一
        // 当前用户可以更新博客....
    }
}

  

 
posted @ 2021-05-25 16:09  小林不会飞  阅读(1788)  评论(0编辑  收藏  举报