我有一个扩展 fos 用户包和另一个包的包。
一旦用户通过身份验证,我希望根据他的角色管理员或简单用户将他重定向到不同的视图。
我的问题是我找不到登录控制器,我将从那里进行重定向。
角色是User
来自数据库的实体的属性。
您必须添加一个实现AuthenticationSuccessHandler 接口的LoginSuccessHandler ,
然后,您可以在onAuthenticationSuccess()
方法中设置重定向逻辑,如下所示,
namespace XXX\YourBundler\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
protected $router;
protected $security;
public function __construct(Router $router, SecurityContext $security)
{
$this->router = $router;
$this->security = $security;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($this->security->isGranted('ROLE_XXXX_1'))
{
$response = new RedirectResponse($this->router->generate('route_1'));
}
elseif ($this->security->isGranted('ROLE_XXXX_2'))
{
$response = new RedirectResponse($this->router->generate('route_2'));
}
// ...
}
}
您的处理程序还必须注册为服务,
parameters:
security.authentication.success_handler.class: XXX\YourBundler\Handler\AuthenticationSuccessHandler
services:
security.authentication.customized_success_handler:
class: %security.authentication.success_handler.class%
public: false
arguments: [@router, @security.context]
然后,您必须将以下行添加到防火墙安全配置中,
success_handler: security.authentication.customized_success_handler
您可以按如下方式覆盖 renderLogin 函数:
class SecurityController extends BaseController
{
/**
* Renders the login template with the given parameters. Overwrite this function in
* an extended controller to provide additional data for the login template.
*
* @param array $data
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function renderLogin(array $data)
{
$securityContext = $this->get('security.context');
$router = $this->container->get('router');
// if ($this->get('security.context')->getToken()->getUser() instanceof \FOS\UserBundle\Propel\User) {
// $url = $this->container->get('router')->generate('dashboard');
// return new RedirectResponse($url);
// }
if ($securityContext->isGranted('ROLE_ADMIN')) {
return new RedirectResponse($router->generate('dashboard'), 307);
}
if ($securityContext->isGranted('ROLE_USER')) {
return new RedirectResponse($router->generate('front_page_home'), 307);
}
$requestAttributes = $this->container->get('request')->attributes;
if ($requestAttributes->get('_route') == 'admin_fos_user_security_login') {
$template = sprintf('FOSUserBundle:Security:login.html.twig');
$data['admin'] = true;
} else {
$template = sprintf('FOSUserBundle:Security:login.html.twig');
$data['admin'] = false;
}
return $this->container->get('templating')->renderResponse($template, $data);
}
}