Instantly share code, notes, and snippets.

Embed
What would you like to do?
Access Denied Flash Message
<?php
namespace AppBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Routing\RouterInterface;
class AccessDeniedHandler implements AccessDeniedHandlerInterface
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function handle(Request $request, AccessDeniedException $accessDeniedException)
{
$request->getSession()->getFlashbag()->add('error', 'Error 403!...');
$url = $this->router->generate('homepage');
return new RedirectResponse($url);
}
}
services:
# ...
app.security.access_denied_handler:
class: AppBundle\Security\AccessDeniedHandler
autowire: true
@geoff-maddock

This comment has been minimized.

geoff-maddock commented May 11, 2018

I made the mistake of adding the flash message inside of the voter classes, which caused flash messages to occur in some cases when I didn't want them to. However, I'd like to be able to pass a message as to why the user was denied to the access denied handler. Any suggestion about how best to do that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment