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?
You can throw an exception at any point in your code:
throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
The exception is then caught by DefaultExceptionHtmlSubscriber and a subrequest for
/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.
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.
From a page, you can use:
return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('your.module.route.name'));
Or from a from submit:
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