我正在使用Symfony 3.4
,并为EventSubscriber
创建了一个KernelEvents::EXCEPTION
。
如何在事件处理程序中访问当前用户?我正在使用以下代码,但它将为用户返回null
/ annon.
。我假定在处理登录过程之前已触发该事件。
class SecurityEventsSubscriber implements EventSubscriberInterface {
...
public static function getSubscribedEvents() {
return array(
KernelEvents::EXCEPTION => array(array('onKernelException', 0)),
);
}
public function onKernelException(GetResponseForExceptionEvent $event) {
$user = null
if ($this->securityContext->getToken() && $this->securityContext->isGranted('ROLE_USER')) {
$exception = $event->getException();
if ($exception instanceof HttpException && $exception->getStatusCode() == 404) {
// Send message to user...
}
} else {
// Always executed since $this->securityContext->getToken()->getUser() return 'annon.'
}
}
}
在此事件处理程序中是否有解决方案来访问当前用户?
编辑:
我想监视是否有用户帐户的not_found,method_not_allowed等错误异常高,以防止可能的攻击。监视这些异常没问题,但是如何获得相应的用户帐户?