我正在使用护照个人访问令牌来保护我的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();
//
}
CategoryController.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());
}
...
您可以看到,我已经使用了管理员作用域,该权限只能由管理员用户访问。但是问题是类别模型只能由admin范围编辑或更新,并且可以由admin和user范围访问。解决这个问题的最佳方法是什么?
一个对我有用的解决方案是我两次使用了不同范围的中间件。
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());
}
...