Cakephp 4 Authorization

@justinkbug, the setup is a little more straightforward than you are imagining. Here is a mapping from my own code:

        $mapResolver->map(IdPackage::class, IdAccessPolicy::class);

with this in place I can check policies anywhere in my app. I just need three things

  1. the Identity object for the Authenticated user, wrapped in an Authorization\IdentityDecorator

  2. an object of the type named as the first argument of my map() call
    (in this case an IdPackage)

  3. a class of the type named as the second argument of my map() call
    (in this case an IdAccessPolicy)

The Identity object should be available and correct if both the Authentication and Authorization plugins are installed properly.

Here is some code that would work:

// assuming $identity is a decorated Identity object
$IdPackage = new IdPackage($tenant_id, 'tenant')
if ($identity->can('edit', $IdPackage) {
  //more code here
}

The IdPackage in will map to IdAccessPolicy as defined in the earlier map() call. And based on this code, we would expect that class to look something like this:

class IdAccessPolicy {

 public function canEdit($identity, $IdPackage) {
   //access logic here
   // return boolean
 }
}

In this way you can easily map any object type to one policy class and implement any kind of policy check you like. As illustrated here, if no naturally occurring object exists that has the data relevant to your needs, you can design one and map to it.

You might also want to look at the Request Authorization Middleware which can authorize each controller/action request before any controller is constructed.

1 Like