Drupal - How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)?

Drupal 8 adds the response header X-Frame-Options: SAMEORIGIN to all pages. This prevents that the content is included in iframes on third party sites.

You can check this for example in the google image search that your content does not appear in the preview frame.

This feature was introduced in drupal 8 beta 13.

The change record

Core is now protected against click-jacking by default (X-Frame-Options: SAMEORIGIN)

is not correct in that the priority has to be higher, in fact it has to be lower. The code example changes the request but it has to change the response.

To provide a solution to the question here is the complete code including the yaml file to put this in the service container:

mymodule/src/EventSubscriber/RemoveXFrameOptionsSubscriber.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RemoveXFrameOptionsSubscriber implements EventSubscriberInterface {

  public function RemoveXFrameOptions(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->remove('X-Frame-Options');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('RemoveXFrameOptions', -10);
    return $events;
  }
}

mymodule/mymodule.services.yml:

services:
  remove_x_frame_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\RemoveXFrameOptionsSubscriber
    tags:
      - { name: event_subscriber }

4k4 give great solution, but also may be

$response->headers->set('X-Frame-Options', 'ALLOW-FROM https://ALLOWED.SITE/');

better then

$response->headers->remove('X-Frame-Options');


The X-Frame-Options header seems to have been added to Drupal 8 in order to prevent click-jacking: https://www.drupal.org/node/2514152

According to the notification above, in order to embed your Drupal site in other sites,

a new Response Subscriber needs to be added that has a higher priority as the current FinishResponseSubscriber (see core.services.yml) to overwrite or remove the header - depending on the use case

It also provides a code example:

<?php
    $path = $request->getPathInfo();

    if (strpos($path, '/fb-app/') === 0) {
      $request->headers->remove('X-Frame-Options');
    }
?>

Tags:

8