Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
drupal

A Drupal subscriber that adds security headers

Blurred lines of source code on a dark screen

Every few months I run a security-header scanner against one of my own sites and get the same grade: a C, for three missing headers. The fix is always "add them in Apache or Traefik", and then a staging box, a dev container or a new hosting setup comes along without that config. I wanted the headers to travel with the codebase, so I put them in a tiny Drupal module instead.

The subscriber

Drupal runs on Symfony's HttpKernel, so the natural hook point is the kernel.response event. Symfony exposes it as KernelEvents::RESPONSE, and the listener receives a ResponseEvent with isMainRequest() and getResponse(). I only touch the main request, because sub-requests (for example ones that build fragments) never reach the browser as a response of their own.

I also inject the router.admin_context service. AdminContext::isAdminRoute() tells me whether the current route is an admin route, which is handy if you want a looser policy there (the toolbar and some admin themes are fussier about framing and embedded content than the front end).

<?php

declare(strict_types=1);

namespace Drupal\my_security_headers\EventSubscriber;

use Drupal\Core\Routing\AdminContext;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Adds baseline security headers to every main response.
 */
final class SecurityHeadersSubscriber implements EventSubscriberInterface {

  /**
   * Headers applied everywhere. Existing values are never overwritten.
   */
  private const DEFAULTS = [
    'X-Content-Type-Options' => 'nosniff',
    'Referrer-Policy' => 'strict-origin-when-cross-origin',
    'Permissions-Policy' => 'camera=(), microphone=(), geolocation=()',
  ];

  public function __construct(
    private readonly AdminContext $adminContext,
  ) {}

  public static function getSubscribedEvents(): array {
    // A negative priority runs late, so we see what other
    // subscribers have already set and can leave it alone.
    return [KernelEvents::RESPONSE => ['onResponse', -10]];
  }

  public function onResponse(ResponseEvent $event): void {
    if (!$event->isMainRequest()) {
      return;
    }

    $headers = $event->getResponse()->headers;

    foreach (self::DEFAULTS as $name => $value) {
      if (!$headers->has($name)) {
        $headers->set($name, $value);
      }
    }

    // Front end only: forbid framing. Admin pages keep Drupal's own policy.
    if (!$this->adminContext->isAdminRoute() && !$headers->has('X-Frame-Options')) {
      $headers->set('X-Frame-Options', 'SAMEORIGIN');
    }
  }

}

Registering it

An event subscriber is just a service tagged event_subscriber. Constructor arguments are the services it needs, referenced with @:

services:
  my_security_headers.subscriber:
    class: Drupal\my_security_headers\EventSubscriber\SecurityHeadersSubscriber
    arguments: ['@router.admin_context']
    tags:
      - { name: event_subscriber }

After a drush cr the service container is rebuilt and the subscriber is live. A quick curl -sI https://example.com/ should show the three headers.

Why the has() check matters

The guard I care most about is !$headers->has($name). If Traefik, Apache or a CDN already adds a stricter value, you don't want the application to quietly replace it, and if a route sets its own Referrer-Policy on purpose, that wins. The module is a floor, not a ceiling.

It also helps to know where this runs relative to caching. Drupal's Internal Page Cache stores the whole response including its headers, so a cached page still carries these headers when it is served. If you later make a header depend on something per-request (a nonce, say), you will need to think about cache contexts or skip caching for that response, which is why I kept the values static.

What this does not do

I deliberately left out Content-Security-Policy and Strict-Transport-Security. A CSP depends on every script and font your theme and contrib modules load, so a naive default will break pages; the Security Kit module is better suited to that, and HSTS is a mistake you can't easily undo, so I keep it at the proxy where TLS terminates. For testing, a kernel test that requests a front-end path and asserts on the response headers is enough to protect this from a refactor.

The result is dull in the best way: three headers, one small class, and a scanner grade that no longer depends on which server the site happens to be running on.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.