How to implement IP-based access checking for REST resources

Created on 10 February 2016, almost 9 years ago
Updated 8 December 2023, 12 months ago

Hi,

I've been struggling on a problem for quite a while. I'm trying to implement a check on ip address before REST request can be made. So far I've been successful in POST, PATCH and DELETE. But GET is a little bit harder.

I implemented "hook_rest_resource_alter" where I altered the class for the resource "entity:node".

/**
 * Implements hook_rest_resource_alter();
 */
function hook_rest_resource_alter(&$definitions) {
  if (isset($definitions['entity:node'])) {
    // Custom access handling to REST request.
    $definitions['entity:node']['class'] = 'Drupal\my_module\Plugin\rest\resource\MyResource';
  }
}

This class extends the default "EntityResource" class. All it does is this:

class MyResource Extends EntityResource{

public function get(EntityInterface $entity) {
    // Check if ip address is in white list.
    if (!in_array($this->clientIp, $this->ipWhiteList)) {
      throw new AccessDeniedHttpException($this->clientIp.' is not allowed to use this resource.');
    }

    return parent::get($entity);
  }
}

Explanation: Check on ip, if ip is in white list, delegate the get-request to the parent class.

This works fine until the parent is successfully called once. At this point Drupal caches the page. The next time when a request is made to the same node, the page is served from cache and drupal doesn't run my check anymore.

Any ideas how I can tackle this problem?
I was hoping to do something like

$entity->invalidateCache();

But this isn't an option :)

πŸ’¬ Support request
Status

Fixed

Version

11.0 πŸ”₯

Component
RoutingΒ  β†’

Last updated 1 day ago

Created by

πŸ‡§πŸ‡ͺBelgium robin.ingelbrecht

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024