我正在尝试创建一个基于拉拉维尔框架的网站。我被困在策略的权限控制中。这是我的代码: + 政策 注册于 :App\Providers\AuthServiceProvider
class 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\UserPolicy
class 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.php
Route::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."
}
任何人都可以指出我的错误吗?
梦里花落0921