描述:
我想在我的 LoginAction 上使用一个监听器,但我正在使用的那个不工作。
我有一个实体:
class User implements AdvancedUserInterface {
public function isEnabled(){}
...
}
}
所以,当我尝试连接我的用户时,我收到了好消息:
user is disabled
在这个 Action 中,我使用这样的 ExceptionListener :
# src/AppBundle/EventListener/ExceptionListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\DisabledException;
class ExceptionListener
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
die('-------');
$ex = $event->getException();
if($ex instanceof DisabledException) {
$url = $this->router->generate('accounts.please_activate');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
我的监听器工作,因为,如果我在构造中执行 die
,没关系,但是,我的 die
在函数 onKernelException 中不起作用
所以我重定向到特定路由不起作用...
services.yml
services:
app.exception_listener:
class: AppBundle\EventListener\ExceptionListener
arguments: ['@router']
tags:
- { name: kernel.event_listener, event: kernel.exception }
问题:
为什么我无法将被视为“已禁用”的用户重定向到特定路由?
另一方面,这被认为是好的做法吗?
最佳答案
您应该使用自定义的登录处理程序来处理登录失败。
创建一个实现 Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface
的新服务:
namespace AppBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\DisabledException;
class FailLoginHandler implements AuthenticationFailureHandlerInterface
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if($exception instanceof DisabledException) {
$url = $this->router->generate('accounts.please_activate');
return new RedirectResponse($url);
}
}
}
定义一个新服务
services:
app.login_fail:
class: AppBundle\Security\FailLoginHandler
arguments: ['@router']
然后在security.yml的防火墙配置下添加failure_handler
选项:
security:
firewalls:
firewallname:
failure_handler: app.login_fail
关于php - Symfony 3 - LoginAction 上的监听器 - kernelException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718670/