laravel - 在 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());
}
...
如您所见,我使用了仅管理员用户可以访问的管理员范围。但问题是类别模型只能由管理员范围编辑或更新,并且可以由管理员和用户范围访问。解决这个问题的最佳方法是什么?
解决方案
一种对我有用的解决方案是我两次使用不同范围的中间件。
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());
}
...
推荐阅读
- sqlite - SQLite decimal(12,2) ,它实际上是如何工作的?
- multithreading - 了解 println("${Thread.currentThread()}") 的输出
- php - 我在将下拉值插入数据库时遇到问题
- javascript - 在函数中使用 id 时替代 eval
- c++ - 欧拉计划:找出 1000 位数字中乘积最大的 13 个相邻数字
- typescript - 使用自己的 Monad 时 Ramda 链的打字稿类型
- javascript - React 输入会在第一次单击时保存输入,然后在第二次单击时将其显示在 UI 中……为什么?!!!以及如何解决它
- leaflet - 如何从自定义 OSM 切片服务器中提取切片?我的 URL 字符串似乎不起作用
- python - 返回每个组和组内每个零的 1 前 0 的计数
- ruby-on-rails - 捆绑更新和安装在 Rails 5 上永远挂起