使用 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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

我认识上,路由一般都不这样写product_image,而是product-image这样。

4年前 评论

@Sloth 路由参数不能包含-符号 :sweat_smile:

路由《Laravel 7 中文文档》

4年前 评论
EmptyCup 4年前
一百万个答案 (作者) (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!