rel*_*lez 2 symfony fosuserbundle symfony-2.3
我试图在用户登录FOSUserBundle后执行一个函数,在我的config.yml中我设置了服务:
services:
authentication.success.listener:
class: MyCompany\MyBundle\EventListener\AuthenticationEventListener
arguments: [@router]
tags:
- { name: kernel.event_subscriber }
Run Code Online (Sandbox Code Playgroud)
然后,我用方法创建Listener类:
<?php
namespace MyCompany\MyBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\UserEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie as Cookie;
class AuthenticationEventListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'onAuthenticationSuccess',
);
}
public function onAuthenticationSuccess(UserEvent $event)
{
//my actions goes here...
}
}
?>
Run Code Online (Sandbox Code Playgroud)
当我尝试登录时,之后没有任何反应,我写了一些错误的代码来生成异常,但一切顺利......显然这个功能并没有被排除在外.
有什么帮助吗?
好吧,经过几个小时的搜索和享受尤文图斯战胜皇家马德里(2-1)后,我找到了一个解决方案.我的解决方案包括修改security.yml中的'success_handler'并创建事件,这是代码:
security:
..
firewalls:
main:
..
success_handler: authentication.success.listener
Run Code Online (Sandbox Code Playgroud)
然后在services.yml中声明服务:
services:
authentication.success.listener:
class: MyCompany\MyBundle\EventListener\AuthenticationEventListener
arguments: ['@router', '@security.context', '@service_container']
Run Code Online (Sandbox Code Playgroud)
然后我声明要监听的类/函数:
// MyCompany\MyBundle\EventListener\AuthenticationEventListener.php
<?php
namespace MyCompany\MyBundle\EventListener;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Router;
class AuthenticationEventListener implements AuthenticationSuccessHandlerInterface
{
protected $router;
protected $security;
protected $container;
protected $em;
public function __construct(Router $router, SecurityContext $security, $container)
{
$this->router = $router;
$this->security = $security;
$this->container = $container;
$this->em = $this->container->get('doctrine')->getEntityManager();
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$response = new Response();
$response = new RedirectResponse('dashboard');
return $response;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我希望它对你们有用...
不管怎么说,多谢拉!
| 归档时间: |
|
| 查看次数: |
2551 次 |
| 最近记录: |