我正在Symfony2中编写一个事件监听器,它监听kernel.response
事件,并在以下情况下添加一个cookie:a)用户登录,b)当前不存在这样的cookie。它将服务容器作为参数。
但是,当侦听器响应不在防火墙后面的事件(例如开发工具栏中的事件)时,我收到错误,因为令牌为空并且抛出了AuthenticationCredentialsNotFoundException
。但是,我不能为我的生活弄清楚如何判断路线是否在防火墙后面。有人可以帮忙吗?
代码
public function onKernelResponse(FilterResponseEvent $event) {
// does the request have a device cookie?
if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')
&& !$this->getRequest()->cookies->has(DeviceManager::COOKIE_PREFIX.'id')) {
// no. Create one.
$DeviceManager = $this->container->get('salus_user.device_manager');
$Cookie = $DeviceManager->createDeviceCookie();
$Response = $event->getResponse();
$Response->headers->setCookie($Cookie); // and save it
}
// else, yes, we don't need to do anything
}
错误
AuthenticationCredentialsNotFoundException in classes.php line 2888:
The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
答案 0 :(得分:2)
首先检查是否存在令牌:
public function onKernelResponse(FilterResponseEvent $event) {
if (!$this->container->get('security.token_storage')->getToken()) {
return;
}
// Rest of code.
}