Symfony2's AccessDeniedHandlerInterface to automatically redirect unauthorized users

匆匆过客 提交于 2020-01-04 06:15:33

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/25062865/symfony2s-accessdeniedhandlerinterface-to-automatically-redirect-unauthorized-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!