首页 > 解决方案 > 基于用户角色的登录后重定向

问题描述

我在 Symfony 3.4 中使用 FosUserBundle。我想根据用户的角色重定向用户。例如,如果角色是客户,用户将被重定向到客户页面。如果用户是管理员,则用户将被重定向到管理员仪表板页面。如何使用 FosUserBundle 做到这一点?

标签: symfonyfosuserbundle

解决方案


将它们重定向到名为indexAction()的控制器,并根据角色将它们重定向到控制器中。像这样的东西:

/**
 * @Route("/secure-area", name="homepage")
 */
public function indexAction()
{

    if($this->getUser()->hasRole('ROLE_ADMIN'))
        return $this->redirect($this->generateUrl('admin_area'));
    elseif($this->getUser()->hasRole('ROLE_USER'))
        return $this->redirect($this->generateUrl('client_area'));
    throw new \Exception(AccessDeniedException::class);
}

编辑: 您应该将default_target_path设置为上面的路径


推荐阅读