CakePhp4 Implementing deprecated Controller::isAuthorized() with the new Authentication & Authorization plugins

I'm looking how to to implement the deprecated Controller::isAuthorized() with the new Authentication & Authorization plugins but I could not find the way.

For example in the method RequestPolicyInterface::canAccess() called by the RequestAuthorizationMiddleware I could not get an instance of the current Controller.

Any idea ??

Thanks.

1 answer

  • answered 2021-04-21 16:26 ndm

    Policies apply to, and receive resources, the request policy applies to requests, and will receive the current request object accordingly, additionally to the current identity which policies do always receive.

    The specific signature for the canAccess method in this case is:

    canAccess(\Authorization\IdentityInterface $identity, \Cake\Http\ServerRequest $request)
    

    eg, the method will receive the current request in the second argument, and you can obtain the routing information from the request parameters::

    public function canAccess($identity, ServerRequest $request)
    {
        if (
            !$request->getParam('plugin') &&
            !$request->getParam('prefix') &&
            $request->getParam('controller') === 'Articles'
        ) {
            return $identity->role->name === 'admin';
        }
    
        return true;
    }
    

    This would allow only users with the role admin to access to the (non-plugin/prefixed) Articles controller, and allow access to all other controller to anyone.

    Note that you will not receive an instance of the controller, as that specific check is a) not made against a controller object but a request object, and b) happens before the controller is even instantiated.

    See also