4

How do I control permissions for API4 calls?

1 Answer 1

5

Events

The API kernel broadcasts an authorise event.

Core permission check listener

The main API permission check subscriber will respond to the event by:

$apiRequest = $event->getApiRequest();   
if ($apiRequest['version'] < 4) { /* blah */ }
elseif ($apiRequest['version'] == 4) {      
  if (!$apiRequest->getCheckPermissions()) {
    $event->authorize();                    
    $event->stopPropagation();              
  }                                         
}                                           

Adding your own listener

If the core logic doesn't meet your needs, it is possible to get the symfony event dispatcher service and add either a listener (for single events) or a subscriber (for multiple events).

For example, to add a subscriber:

$subscriber = new MySubscriberClass();            
\Civi::service('dispatcher')->addSubscriber($subscriber);

When your listener/subscriber is called, then call the $event->getApiRequest() to find out the parameters you are being asked to authorise. If the event should be authorised then call $event->authorize().

SQL clauses

For actions based on get(), the selectQuery->getAclClause() method will call $baoName::getSelectWhereClause($tableAlias) to add a where clause.

It doesn't seem possible currently to apply differing ACL logic depending on the action with this method.

4
  • 2
    Excellent, thanks for documenting this. One caveat, the api4 is currently unstable and by the time it's released this information may be out-of-date.
    – Coleman
    Commented Mar 12, 2017 at 0:14
  • @Coleman it's 5 years later, but I think this answer is still ok, right? Commented Jan 4, 2023 at 11:54
  • @artfulrobot Yes there's also a permissions() function you can put in the api4 entity file, to control gatekeeper permissions. Otherwise the BAO generally handles permissions.
    – Coleman
    Commented Jan 4, 2023 at 23:34
  • @Coleman thanks for update. I guess the event method is useful primarily when wanting to alter core API permissions. Commented Jan 5, 2023 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.