Drupal - Show access denied in custom page without permissions

As a replacement for drupal_access_denied() this in Drupal 8 you can use :

if(empty($userId)){

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

}

This shows the access denied page in the browser.


Throwing an access denied exception is possible, but if you have a controller that is only accessible for that user, you should use an access requirement on that route instead:

requirements:
  _custom_access: '\Drupal\comment\Controller\CommentController::replyFormAccess'

That method can then check access and return an access result object.

The advantage of this is that access can already be checked during routing, and menu links and other places that point to such a page can automatically check access and decide to hide the link. That is not possible when throwing an access denied exception, as you would have to open up the route to everyone (_access: true) as the default is not accessible for anyone.


You can throw an exception:

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

  if ( $userid != '123' ) {
    throw new AccessDeniedHttpException();
  }

Tags:

8