我正在使用FOSUserBundle软件包使用Symfony 2构建Web应用程序 用户创建帐户,登录并开始使用该应用程序。
我现在想要实现的目标是让用户从他们登录的任何页面重定向到他们的帐户。
这包括:
基本上代码是这样的:
$container = $this->container;
$accountRouteName = "DanyukiWebappBundle_account";
if( $container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
// authenticated (NON anonymous)
$routeName = $container->get('request')->get('_route');
if ($routeName != $accountRouteName) {
return $this->redirect($this->generateUrl($accountRouteName));
}
}
问题是我不知道代码应该去哪里。
它应该针对任何请求执行。在Symfony 1中,我会使用过滤器。
答案 0 :(得分:31)
我自己找到了解决方案:
<?php
namespace Danyuki\UserBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LoggedInUserListener
{
private $router;
private $container;
public function __construct($router, $container)
{
$this->router = $router;
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
$container = $this->container;
$accountRouteName = "DanyukiWebappBundle_account";
if( $container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
// authenticated (NON anonymous)
$routeName = $container->get('request')->get('_route');
if ($routeName != $accountRouteName) {
$url = $this->router->generate($accountRouteName);
$event->setResponse(new RedirectResponse($url));
}
}
}
}
然后,在我的bundle的services.yml文件中:
services:
kernel.listener.logged_in_user_listener:
class: Danyuki\UserBundle\Listener\LoggedInUserListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
arguments: [ @router, @service_container ]
答案 1 :(得分:1)
如果您只想检查一次,也可以执行此解决方案:
每次成功登录都会触发一个事件。 该活动名称为:
security.interactive_login
为了订阅此事件,您必须使用您创建的类创建一个服务容器,然后使用“LoginListener.php”并使用事件“security.interactive_login”注入标记“kernel.even_listener”:
<service id="mylogin.success.listener" class="path\to\class\LoginListener">
<tag name="kernel.event_listener" event="security.interactive_login" method="onLoginSuccess" />
</service>
LoginListener中的:
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
public function onLoginSuccess(InteractiveLoginEvent $event) {
if ($this->_security->isGranted('IS_AUTHENTICATED_FULLY')) {
//your code here...
}
}
您还可以添加其他依赖项并将其注入构造函数,在我的情况下,我必须注入安全性,会话和容器:
public function __construct(SecurityContext $security, Session $session, ContainerInterface $container) {
}