使用 authorizeResource 资源授权时的坑
在控制器中使用 authorizeResource
授权时,凡是路由参数是蛇形命名法(snake case)命名的,例如product_image
Route::resource('product/{product}/product_image', 'ProductImageController')
public function __construct()
{
$this->authorizeResource(ProductImage::class, 'product_image');
}
控制器的update()
和destroy()
动作都会未经授权验证,直接报出 403 This action is unauthorized.
错误
参考:https://github.com/laravel/framework/issue...
authorizeResource(\App\Post::class, ‘post’) and controller method update($post_id) will give a 403 error without reaching ever the policy.
解决办法:
public function boot()
{
parent::boot();
Route::model('product_image', ProductImage::class);
}
在 RouteServiceProvider
中显式绑定路由参数与对应模型。
使用重命名路由参数也可以解决问题,参考:https://github.com/laravel/framework/issue...
Route::resourc('posts', ' UserPostsController', ['parameters' => ['posts' => 'user_post']]);
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: