我正在尝试创建一个基于拉拉维尔框架的网站。我被困在策略的权限控制中。这是我的代码: + 政策 注册于 :App\Providers\AuthServiceProviderclass AuthServiceProvider extends ServiceProvider{ protected $policies = [ User::class => UserPolicy::class, Category::class => CategoryPolicy::class ]; public function boot() { $this->registerPolicies(); try { Permission::all()->each(function($permission) { Gate::define($permission->name, function ($user) use($permission) { return $user->hasPermission($permission->name); }); }); } catch (\Exception $e) { Log::notice('Unable to register gates. Either no database connection or no permissions table exists.'); } }}用户策略 在App\Policies\UserPolicyclass UserPolicy{ use HandlesAuthorization; public function viewAny(User $user) { return true; } public function view(User $user, User $target_user) { return $user->id === $target_user->id; }}阿皮航线routes/api.phpRoute::get('/users', 'Api\UserController@getUsers')->middleware('can:view-users');Route::get('/users/{user_id}', 'Api\UserController@getUser')->middleware('can:view-users');Route::put('/users/{user_id}', 'Api\UserController@updateUser')->middleware('can:edit-users');用户控制器 在App\Http\Controllers\Api\UserController public function getUsers(UserRequest $request) { $users = $this->userRepository->getAll(); $this->authorize('view', $user); return response($users, 200); } public function getUser(UserRequest $request, $user_id) { $user = $this->userRepository->find($user_id); $this->authorize('view', $user); return response($user, 200); }当我尝试使用上面的2 url获取数据时,即使用户经过身份验证,它也返回错误:500 Internal Server Error{ "error": "This action is unauthorized."}任何人都可以指出我的错误吗?
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
解决。在图书馆阅读源代码几个小时后,我发现了问题。我为我的应用程序使用了警卫,没有模块。因此,类中的变量无法设置为经过身份验证的用户并获取值。为了解决这个问题,我创建了自己的中间件,而不是laravel中间件,并用于获取经过身份验证的用户。api
passport
$userResolver
Illuminate\Auth\Access\Gate
null
Authorize
Authorize
Auth::guard('api')->user()
- 1 回答
- 0 关注
- 66 浏览
添加回答
举报
0/150
提交
取消