How to redirect to different url based on roles in symfony 2

Viewed 16304

I have one login page on site. I have 4 different tye of users and i want that when they login they go to different page based on their role assigned.

Is there any way?

7 Answers

I used this in the login Form authenticator to redirect user based on role (symfony : 4.26.8) :

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;

private $urlGenerator;
/**
 * @var Security
 */
private $security;

public function __construct(UrlGeneratorInterface $urlGenerator ,Security $security)
{
    $this->urlGenerator = $urlGenerator;
    $this->security = $security;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {        
    // redirecting user by role : 
        $user = $this->security->getUser();
        $roles = $user->getRoles();
        $rolesTab = array_map(function($role){
            return $role;
        }, $roles);
        if (in_array('ROLE_ADMIN', $rolesTab) || in_array('ROLE_SUPER_ADMIN', $rolesTab)) {
            return new RedirectResponse($this->urlGenerator->generate('admin'));
        }
        else{
            return new RedirectResponse($this->urlGenerator->generate('home'));
    }
}
Related