【发布时间】:2020-09-27 01:41:56
【问题描述】:
我在App\Policies\UserPolicy 下为UserController 创建了一个用户策略,只允许ID 为2 的用户访问。但是现在即使是 id 为 1 的用户也可以访问而不会抛出任何错误。
/**
* Determine whether the user can create models.
*
* @param \App\Models\Auth\User $user
* @return mixed
*/
public function create(User $user)
{
return $user->id === 2 ? Response::allow()
: Response::deny('You do not own this users.');;
}
路线:
Route::get('user/createProfile' , [UserController::class, 'showCreateProfileForm'])->name('user.profile.createProfile');
控制器:
UserController.php
public function showCreateProfileForm()
{
$user = Auth::user();
$this->authorize('create' , $user);
return view('backend.auth.user.profile.create');
}
提供者:AuthServiceProvider.php
<?php
namespace App\Providers;
use Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Models\Auth\User;
use App\Policies\UserPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
User::class => UserPolicy::class,
];
/**
* Register any authentication / authorization services.
*/
public function boot()
{
$this->registerPolicies();
}
}
当我从 UserController@showCreateProfileForm 返回 $this->authorize('create' , $user); 时,它会不断返回
{
"allowed": true,
"message": null,
"code": null
}
【问题讨论】:
-
请尝试:$this->authorize('create');并确保你有: $this->authorizeResource(User::class, 'user');在你的控制器构造函数中
-
不,它不起作用,甚至没有注册该政策。