'What is the correct way to use authorization policy class to authorize access to an index page in cakephp4?

I developed a few cakephp3 apps, and now I'm learning how to use cakephp4. I'm trying to centralize all my authorization logic in the *Policy classes. I have a situation where a user wants to access a entity/index page, and I want to validate if he can access this index page by doing some queries.

So right now I'm using $this->Authorization->authorize($this->Entity->newEmptyEntity()); in the controller, in order to be able to access an EntityPolicy->canIndex() method. Is there a more elegant way to do it, to call a policy method without an instance of the entity?

After that, in order to be able to run my queries, I'm using the ModelAwareTrait in the class, and querying data in a similar way that I do in controllers. Is there a better approach?



Solution 1:[1]

Send the entity itself. For example, if you are using the Articles controller

$this->Authorization->authorize($this->Articles);

$this->Authorization->can($this->Articles,'index')

While declaring the canIndex() method normally in your Policy.

Solution 2:[2]

My solution was somewhat different (and easier I guess)

//In my ProjectController.php
  public function index()
  {
    $project = new Project();
    $this->Authorization->authorize($project);
  }

this way I don't have to do a useless query (I just create an empty Project object), but at the same time I can check the user attributes. In my case the solution proposed by @eos (above) didn't work, because calling

    $this->Authorization->authorize($this->Projects);

lead to an unwanted result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eos
Solution 2 massimoi