Skip to content
Snippets Groups Projects

Issues/3490087: Use CSRF token in API endpoints.

Files
5
@@ -5,7 +5,9 @@ declare(strict_types=1);
@@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Drupal\experience_builder\EventSubscriber;
namespace Drupal\experience_builder\EventSubscriber;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
 
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\RouteMatchInterface;
 
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelEvents;
@@ -15,7+17,7 @@
@@ -15,7+17,7 @@
*
*
* @internal
* @internal
*/
*/
final class XbRouteOptionsEventSubscriber implements EventSubscriberInterface {
final class XbRouteOptionsEventSubscriber implements EventSubscriberInterface {
public function __construct(
public function __construct(
private readonly RouteMatchInterface $routeMatch,
private readonly RouteMatchInterface $routeMatch,
@@ -37,7+39,7 @@
@@ -37,7+39,7 @@
}
}
}
}
 
public function addCsrfToken(RouteBuildEvent $event): void {
 
foreach ($event->getRouteCollection() as $name => $route) {
 
if (str_starts_with($name, 'experience_builder.api.') &&
 
// Drupal's AJAX submits to these URL and doesn't know that it needs to
 
// add an X-CSRF-Token header. These routes use Drupal's form API which
 
// already includes CSRF protection via a hidden input.
 
$route->getOption('_wrapper_format') !== 'xb_template') {
 
if (array_intersect($route->getMethods(), ['POST', 'PATCH', 'DELETE'])) {
 
$route->setRequirement('_csrf_request_header_token', 'TRUE');
 
}
 
}
 
}
 
}
 
/**
/**
* {@inheritdoc}
* {@inheritdoc}
*/
*/
public static function getSubscribedEvents(): array {
public static function getSubscribedEvents(): array {
$events[KernelEvents::REQUEST][] = ['transformWrapperFormatRouteOption'];
$events[KernelEvents::REQUEST][] = ['transformWrapperFormatRouteOption'];
 
$events[RoutingEvents::ALTER][] = ['addCsrfToken'];
return $events;
return $events;
}
}
Loading