0

I want to show a "Access denied" (403) page with message "You are not authorized to access this page." for a given route. This will apply to all users in any case.

How to do it in the simplest way?

1 Answer 1

0

Just implement a route subscriber like this:

In MYMODULE/src/EventSubscriber/RouteSubscriber.php:

<?php

namespace Drupal\MYMODULE\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection): void {
    // Remove access to page with route "given.route".
    if ($route = $collection->get('given.route')) {
      $route->setRequirement('_access', 'FALSE');
    }
  }
}

Please note the quotes around FALSE!

Of course the route subscriber needs to be declared in the services file of the custom module.

In MYMODULE/services.yml

services:
  MYMODULE.route_subscriber:
    class: Drupal\MYMODULE\EventSubscriber\RouteSubscriber
    tags:
      - { name: event_subscriber } 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.