我在FOSUserBundle中使用“ success_handler ”(在Symfony security.yml中)和 onLogoutSuccess()。但是我想让getUser()在flash消息中添加他的名字。
服务和PHP Classe:
services:
utilisateur_deconnexion:
class: UtilisateurBundle\Handler\Deconnexion
arguments: [@router]
class Deconnexion implements LogoutSuccessHandlerInterface
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onLogoutSuccess(Request $request)
{
$request->getSession()->getFlashBag()->add('success', 'Vous êtes à présent déconnecté.');
return new RedirectResponse($this->router->generate('dometech_index_index'));
}
}
你能帮助我吗?
答案 0 :(得分:2)
您可以将@security.context
服务注入您的注销处理程序。
从SecurityContext,您将能够获得当前设置的令牌对象,该对象是TokenInterface的实例。从TokenInterface
的实例中,您将能够获得当前用户。见下文。
<强> services.yml 强>
services:
utilisateur_deconnexion:
class: UtilisateurBundle\Handler\Deconnexion
arguments: ["@router", "@security.context"]
退出成功处理程序:
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Routing\RouterInterface;
class Deconnexion implements LogoutSuccessHandlerInterface
{
private $router;
private $securityContext;
public function __construct(RouterInterface $router, SecurityContextInterface $securityContext)
{
$this->router = $router;
$this->securityContext = $securityContext;
}
public function onLogoutSuccess(Request $request)
{
// let's assume your user object has getUsername method
$username = $this->securityContext->getToken()->getUser()->getUsername();
$request->getSession()->getFlashBag()->add(
'success',
sprintf('%s - Vous êtes à présent déconnecté.', $username)
);
return new RedirectResponse($this->router->generate('dometech_index_index'));
}
}
答案 1 :(得分:0)
完成/更新Symfony 3.x的@takeit帖子
将@security.context
替换为@security.token_storage
<强> services.yml 强>
services:
utilisateur_deconnexion:
class: UtilisateurBundle\Handler\Deconnexion
arguments: ["@router", "@security.token_storage"]
退出成功处理程序:
[...]
public function onLogoutSuccess(Request $request)
{
// let's assume your user object has getUsername method
$username = $this->tokenStorage->getToken()->getUsername();
[...]
}
[...]