Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Created March 22, 2017 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaverryan/492b8c8661c6c7248891c61447495f12 to your computer and use it in GitHub Desktop.
Save weaverryan/492b8c8661c6c7248891c61447495f12 to your computer and use it in GitHub Desktop.
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
Copy link

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