Laravel 通过中间件授权

Ham*_*ani 6 php laravel laravel-5

我使用以下两个操作在 laravel 5.3 中创建了一个策略:

class ProjectPolicy {
   ...
   public function index(User $user)
   {
      return true;
   }
   public function create(User $user)
   {
      return true;
   }
   ...
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试通过路由组中间件进行授权:

Route::group(['middleware' => ['can:index,create,App\Project']], function () {
    Route::resource('projects', 'ProjectController');
});
Run Code Online (Sandbox Code Playgroud)

当然我已经正确创建了项目模型和控制器,但是调用索引和创建操作总是返回 403 禁止响应。问题出在哪儿?

更新:

从路由中间件中删除操作之一,结果正确响应。像这样:

Route::group(['middleware' => ['can:index,App\Project']], function () {
    Route::resource('projects', 'ProjectController');
});
Run Code Online (Sandbox Code Playgroud)

Rwd*_*Rwd 4

通过查看文档,can中间件并没有真正提供资源。您可以在组上使用多个中间件调用,但这意味着您的使用需要所有权限才能访问路由。

您的替代方案是:

添加$this->authorize(new App\Project)到控制器中的index和方法。createLaravel 将使用反射来根据调用它的方法来确定要使用的策略。

或者

__construct()控制器的方法中,您可以使用:

$this->authorizeResource(App\Project::class); 
Run Code Online (Sandbox Code Playgroud)

这将要求您在 Policy 类中创建update,view和方法。delete这些方法中的每一个都将被传递,User $user, Project $project例如

public function view(User $user, Project $project)
{
   return true;
}
Run Code Online (Sandbox Code Playgroud)

仅供参考,如果您省略方法名称authorize()或使用authorizeResource()Laravel 会将某些方法名称映射到不同的策略方法,即:

[
  //ControllerMethod => PolicyMethod
    'show'    => 'view',
    'create'  => 'create',
    'store'   => 'create',
    'edit'    => 'update',
    'update'  => 'update',
    'destroy' => 'delete',
];
Run Code Online (Sandbox Code Playgroud)

resourceAbilityMap()您可以通过向控制器添加一种方法并返回与上述数组不同的数组来覆盖此设置。

希望这可以帮助!