Laravel - 授权仅适用于控制器方法
Laravel - Authorization Works from Controller Method only
我已经设置了我的模型策略,当我从控制器操作中授权操作时它似乎正在工作。
// create action
public function create()
{
$this->authorize('create', BusinessProfile::class);
return view('business-profile.create');
}
创建简单 returns true 或 false 并切换布尔值的策略似乎正在工作,因为我基于它获得授权。
这表明我的政策设置正确。
但是,我没有在我的控制器中到处使用 authorize
方法,而是尝试在我的构造函数中设置中间件。
Laravel 文档显示了这个例子。
Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,App\Post');
所以,我在我的控制器构造函数中写了这个。
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:create,BusinessProfile')->only('create');
}
但是,在执行此操作时,该操作始终是未经授权的。
奖金信息
我继续在我的政策中编写垃圾代码以引发语法错误,但我仍然收到未经授权的响应,告诉我我的政策根本没有触发。可能是我没有正确注册我的保单,但如上所述,$this->authorize(...)
按预期工作。
您似乎在模型中使用了别名,而它需要模型名称。在文档状态下:
some actions like create may not require a model instance. In these
situations, you may pass a class name to the middleware. The class
name will be used to determine which policy to use when authorizing
the action:
您可以在此处找到更多信息:https://laravel.com/docs/5.4/authorization#policy-methods
所以在控制器构造函数中这一行:
$this->middleware('can:create,BusinessProfile')->only('create');
将变为:
$this->middleware('can:create,App\BusinessProfile')->only('create');
我已经设置了我的模型策略,当我从控制器操作中授权操作时它似乎正在工作。
// create action
public function create()
{
$this->authorize('create', BusinessProfile::class);
return view('business-profile.create');
}
创建简单 returns true 或 false 并切换布尔值的策略似乎正在工作,因为我基于它获得授权。
这表明我的政策设置正确。
但是,我没有在我的控制器中到处使用 authorize
方法,而是尝试在我的构造函数中设置中间件。
Laravel 文档显示了这个例子。
Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,App\Post');
所以,我在我的控制器构造函数中写了这个。
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:create,BusinessProfile')->only('create');
}
但是,在执行此操作时,该操作始终是未经授权的。
奖金信息
我继续在我的政策中编写垃圾代码以引发语法错误,但我仍然收到未经授权的响应,告诉我我的政策根本没有触发。可能是我没有正确注册我的保单,但如上所述,$this->authorize(...)
按预期工作。
您似乎在模型中使用了别名,而它需要模型名称。在文档状态下:
some actions like create may not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action:
您可以在此处找到更多信息:https://laravel.com/docs/5.4/authorization#policy-methods
所以在控制器构造函数中这一行:
$this->middleware('can:create,BusinessProfile')->only('create');
将变为:
$this->middleware('can:create,App\BusinessProfile')->only('create');