One solution to the problem is to pass the SecurityContext object as an argument to the AccessDeniedHandlerInterface
in the config.yml
file like so.
//config.yml
kernel.listener.access_denied_listener:
class: Path\To\Your\Class
arguments: [@security.context]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: handle }
Doing this allows the handle()
method access to the token representing the current user authentication. From this the appropriate re-routing can take place.
namespace Path\To\Your\Class;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
class AccessDeniedListener implements AccessDeniedHandlerInterface
{
protected $security;
public function __construct(SecurityContext $security)
{
$this->security = $security;
}
public function handle(Request $request, AccessDeniedException $accessDeniedException)
{
if ($this->security->isGranted('ROLE_USER')) {
return new RedirectResponse('user_route');
}
}
}