使用 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 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2

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

4年前 评论

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

路由《Laravel 7 中文文档》

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

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