Ip restriction for api key?

Hi, I would like to restrict the usage of an api key for a white listed ip addresses. What would be the best way to achieve this.

I could probably do something like this

$app->on('collections.save.before.yourcollectionname', function($name, &$entry, $isUpdate) {
    if($apikey == "MY_API_KEY") {
        $allowed = $app->module('collections')->findOne('linked_col_name', ['ip' => $_SERVER['REMOTE_ADDR']]);
        if (!$allowed) {
            return 401;
        }
    }
});

But I don’t know how to get the api key from request at this point.

So, how can I get the api key from request or if not possible is there another way to do this?

Thanks

UPDATE:
Referencing this class https://github.com/agentejo/cockpit/blob/fc4db8a038d865fdd4e4faac911d117b741f4c7f/modules/Cockpit/rest-api.php

I tried to modify modules/Cockpit/bootsrap.php which also didn’t work

// REST
if (COCKPIT_API_REQUEST) {

    // INIT REST API HANDLER
    include_once(__DIR__.'/rest-api.php');

    $this->on('cockpit.rest.init', function($routes) {
        $token = $this->param('token', $this->request->server['HTTP_COCKPIT_TOKEN'] ?? $this->helper('utils')->getBearerToken());
        if($token == "MY_API_KEY") {
            $allowed = $app->module('collections')->findOne('whitelist', ['ip' => $_SERVER['REMOTE_ADDR']]);
            if (!$allowed) {
                return 401;
            }
        }
        $routes['cockpit'] = 'Cockpit\\Controller\\RestApi';
    });
}

create following file: config/bootstrap.php with the following content:

<?php

$app->on('cockpit.rest.init', function() {

    if (!in_array($this->request->getClientIp(), ['172.1.1.1', '172.1.1.2'])) {
        $this->stop(401); // Unauthorized
    }
});

Thank you for the reply.