11

I would like to programmatically redirect my users to the default "access restricted" page. I know that I need a "RedirectResponse" object for a simple redirect, but how do I specify the default "access restricted" page here?

  • 1
    Usually, a "access restricted" page is produced by returning a 403 status code, not redirecting to another page. Did you try something like return new Response('', Response::HTTP_FORBIDDEN); – Pierre Buyle Sep 22 '16 at 15:21
21

You can throw an exception at any point in your code:

403:

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

404:

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

The exception is then catched by DefaultExceptionHtmlSubscriber and a subrequest for /system/403 or /system/404 is returned, which you can configure in the basic site settings if you don't want to display a generic "access denied" or "not found" page.

Other options depend on where the code is placed:

  • Return a 403 or 404 response from a controller or a form

  • Set a response in an event if you are in an event subscriber.

What you should never do is to send a response directly. This doesn't stop the code and produces two responses, one you've sent and one returned by the Drupal kernel. This will result in unpredictable behavior.

2

This seems to be the right way:

    $response = new RedirectResponse('/system/403');
    $event->setResponse($response);
0

From a page, you can use:

return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('your.module.route.name'));

like : http://www.drupal8.ovh/en/tutoriels/88/page-redirection-on-drupal-8

Or from a from submit:

$form_state->setRedirect('your.module.route.name');

Then configure access permission of 'your.module.route.name'

If you dont know how to configure access permision, check: http://www.drupal8.ovh/en/tutoriels/66/create-a-custom-permission-drupal-8

  • I have tried $response = new Response('', Response::HTTP_FORBIDDEN); $event->setResponse($response); this shows only a white page to the user. That's too less information. I want to show the default "access denied" page from Drupal. – jepster Sep 23 '16 at 16:31
0

Build your redirect from the system's access denied route.

$url = Url::fromRoute('system.403');
$response = new RedirectResponse($url->toString());

This takes you to the Drupal standard access denied page. The route is defined in system.routing.yml in core.

The top answer will give you a broken looking browser based Access Denied, which may be what you're looking for. If you want your Drupal UI to show, use the above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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