In Drupal 8, what is the correct way of returning access denied to a user (outside of access requirement on a controller)?

I'd say it is to throw an AccessDeniedHttpException most of the time, but I have seen modules set an event response to 403, or do a redirect response to system.403.

Generally, the correct way is to throw new AccessDeniedHttpException() over setting a 403 or a redirect response, which bypasses the exception handling, so that it's no longer possible to configure a different handling of 403's in contrib or custom code. Unless you want to bypass this intentionally, for example if you want to produce a faster 403.

However, in most cases it is preferable to control the access as route requirement. The main effect is the same, the routing system throws an exception as well. But it does other things, like controlling the visibility of menu links, which you don't get when you throw the exception in custom code.

  • So if you are responding to an Event (onRequest), its fine to do a RedirectResponse to system.403 over throw an exception? An exception seems to make more sense to me. – Kevin Dec 4 at 19:04
  • 1
    Yes, the exception does make more sense. Then the default exception handler can set the 403 response for system.403, without a redirect, but with a subrequest keeping the original URL in the address bar. – 4k4 Dec 4 at 19:24

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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