我正在尝试根据注册/登录后的角色重定向路由。注册后,我将路由重定向到该secure_area,以根据用户角色进行路由。
/**
* @Route("/secure", name="secure_area")
* @throws \Exception
*/
public function indexAction(){
if ($this->isGranted('ROLE_USER1'))
return $this->redirectToRoute('user1');
elseif ($this->isGranted('ROLE_USER2'))
return $this->redirectToRoute('user2');
throw new \Exception(AccessDeniedException::class);
}
[在两种情况下,我都将到达路线user1。如何使其根据用户角色重定向路由?
security.yaml
role_hierarchy:
ROLE_ADMIN: ROLE_USER2
ROLE_USER2: ROLE_USER1
ROLE_USER1: ROLE_USER1
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/user2, roles: ROLE_USER2 }
- { path: ^/user1, roles: ROLE_USER1 }
<?php
// Change the namespace according to the location of this class in your bundle
namespace AppBundle\Listeners;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LoginListener
{
protected $userManager;
protected $router;
protected $security;
protected $dispatcher;
public function __construct(UserManagerInterface $userManager, Router $router, SecurityContext $security, EventDispatcher $dispatcher)
{
$this->userManager = $userManager;
$this->router = $router;
$this->security = $security;
$this->dispatcher = $dispatcher;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
}
public function onKernelResponse(FilterResponseEvent $event)
{
// Important: redirect according to user Role
if ($this->security->isGranted('ROLE_ADMIN')) {
$event->setResponse(new RedirectResponse($this->router->generate("admin_homepage")));
} elseif ($this->security->isGranted('ROLE_MANAGER')) {
$event->setResponse(new RedirectResponse($this->router->generate("manager_homepage")));
} else {
$event->setResponse(new RedirectResponse($this->router->generate("default_homepage")));
}
}
}
您可以像这样实现LoginListener
,它将处理您基于角色的重定向。