Score:0

How to forbid acess to a page?

in flag

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?

Score:0
in flag

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 } 
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.