DrColza
DrColza

Reputation: 110

Symfony2's AccessDeniedHandlerInterface to automatically redirect unauthorized users

When implementing an AccessDeniedHandlerInterface to catch any AccessDeniedExceptions is it possible to access the role of the user in order to determine an appropriate RedirectResponse route?

I want to direct people who aren't logged in to one place, and people that are logged in but don't have the permissions to another place, instead of just getting a 403 page.

Upvotes: 2

Views: 900

Answers (1)

DrColza
DrColza

Reputation: 110

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');
        }
    }
}

Upvotes: 3

Related Questions