首页 > 解决方案 > 在 api 资源方法上有条件地应用 Passport 范围

问题描述

我正在使用护照个人访问令牌来保护我的 API。以下是一些代码片段。

// api.php
Route::apiResource('categories', 'CategoryController');

AuthServiceProvider.php

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

        //scopes 
        Passport::tokensCan([
            'admin' => 'Perform every action',
            'user' => 'Perform only normal user actions',
        ]);

        // passport routes
        Passport::routes();
        //
    }

类别控制器.php

class CategoryController extends Controller
{
    function __construct()
    {
        $this->middleware('api:auth', ['scopes: admin']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {   
        return CategoryResource::collection(Category::all()); 
    }
    ...

如您所见,我使用了仅管理员用户可以访问的管理员范围。但问题是类别模型只能由管理员范围编辑或更新,并且可以由管理员和用户范围访问。解决这个问题的最佳方法是什么?

标签: laravellaravel-passportlaravel-7scopes

解决方案


一种对我有用的解决方案是我两次使用不同范围的中间件。

class CategoryController extends Controller
{
    function __construct()
    {
        $this->middleware('api:auth', ['scopes: admin'])->except(['index']);
        $this->middleware('api:auth', ['scopes: user'])->only(['index']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {   
        return CategoryResource::collection(Category::all()); 
    }
    ...

推荐阅读