<?php
// In your_module/src/EventSubscriber/CustomHeaderSubscriber.php
namespace Drupal\custom\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Response;
/**
* Event subscriber to check for a custom header in incoming requests.
*/
class CustomHeaderSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
// Subscribe to the request event, with a priority of 30
$events[KernelEvents::REQUEST][] = ['checkCustomHeader', 30];
return $events;
}
/**
* Checks for the presence of a custom header in API requests.
*/
public function checkCustomHeader(RequestEvent $event) {
$request = $event->getRequest();
// Define the name of the custom header to check
$customHeaderName = 'Custom-Header';
// Check if the request is an API call (URL path starts with '/api/')
$isApiRequest = strpos($request->getPathInfo(), '/api/') === 0;
// If it's an API request and the custom header is missing, deny access
if (!$request->headers->has($customHeaderName) && $isApiRequest) {
throw new AccessDeniedHttpException('Invalid header token.');
}
// If it's an API request and the header is present, validate the value
else if ($isApiRequest) {
$api_key_value = $request->headers->get($customHeaderName);
// Check if the custom header value is valid (e.g., '12345')
if ($api_key_value !== '12345') {
throw new AccessDeniedHttpException('Invalid header token.');
}
}
}
}
Comments
Post a Comment