我正在嘗試創(chuàng)建一個基于拉拉維爾框架的網(wǎng)站。我被困在策略的權(quán)限控制中。這是我的代碼: + 政策 注冊于 :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); }當(dāng)我嘗試使用上面的2 url獲取數(shù)據(jù)時,即使用戶經(jīng)過身份驗證,它也返回錯誤:500 Internal Server Error{ "error": "This action is unauthorized."}任何人都可以指出我的錯誤嗎?
1 回答

夢里花落0921
TA貢獻(xiàn)1772條經(jīng)驗 獲得超6個贊
解決。在圖書館閱讀源代碼幾個小時后,我發(fā)現(xiàn)了問題。我為我的應(yīng)用程序使用了警衛(wèi),沒有模塊。因此,類中的變量無法設(shè)置為經(jīng)過身份驗證的用戶并獲取值。為了解決這個問題,我創(chuàng)建了自己的中間件,而不是laravel中間件,并用于獲取經(jīng)過身份驗證的用戶。api
passport
$userResolver
Illuminate\Auth\Access\Gate
null
Authorize
Authorize
Auth::guard('api')->user()
- 1 回答
- 0 關(guān)注
- 85 瀏覽
添加回答
舉報
0/150
提交
取消