2015-01-07 2 views
2

Цель состоит в том, чтобы что-то сделать после успеха аутентификации в Symfony2.Удаленный обработчик не работает после входа в систему Symfony2

Для этого я продлил AuthenticationSuccessHandlerInterface, создав службу для входа в форму, чтобы быть ее успешным обработчиком.

Вот брандмауэр в security.yml файле (где объявлен обработчик успеха):

firewalls: 
    main: 
     pattern: ^/ 
     form_login: 
      check_path: fos_user_security_check 
      provider: fos_userbundle 
      csrf_provider: form.csrf_provider 
      success_handler: foo_user.component.authentication.handler.login_success_handler 
     logout:  true 
     anonymous: true 

Вот LoginSuccessHandler сервис (создан в UserBundle):

namespace Foo\UserBundle\Component\Authentication\Handler; 

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\Request; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Routing\Router; 

class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface 
{ 

    protected $router; 
    protected $security; 

    public function __construct(Router $router, SecurityContext $security) 
    { 
     $this->router = $router; 
     $this->security = $security; 
    } 

    public function onAuthenticationSuccess(Request $request, TokenInterface $token) 
    { 
     $referer_url = $request->headers->get('referer');      
     $response = new RedirectResponse($referer_url); 

     return $response; 
    } 
} 

И вот services.xml от UserBundle:

<?xml version="1.0" encoding="utf-8"?> 

<container xmlns="http://symfony.com/schema/dic/services" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://symfony.com/schema/dic/services 
http://symfony.com/schema/dic/services/services-1.0.xsd"> 
    <parameters> 
     <parameter key="foo_user.component.authentication.handler.login_success_handler.class"> 
      Foo\UserBundle\Component\Authentication\Handler\LoginSuccessHandler 
     </parameter> 
    </parameters> 
    <services> 
     <service id="foo_user.component.authentication.handler.login_success_handler" 
     class="%foo_user.component.authentication.handler.login_success_handler.class%"> 
      <tag name="monolog.logger" channel="security"/> 
      <argument type="service" id="router"/> 
      <argument type="service" id="security.context"/> 
      <argument type="service" id="service_container"/> 
     </service> 
    </services> 
</container> 

LoginSuccessHandler вызывает конструктор, и я не получаю сообщений об ошибках.

Проблема, с которой я столкнулся, заключается в том, что onAuthenticationSuccess не вызывается после успешного входа в систему. Может быть, я что-то упустил?

+0

Ну, я думаю, что все выглядит просто отлично, кроме того, что тег сервиса 'monolog.logger'. Это может быть причиной? –

+0

Я попытался удалить это, но проблема остается прежней. – rfc1484

ответ

2

В моих рабочих растворах I реализует метод onSecurityInteractiveLogin в моем слушателе как:

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) 
    { 
     $user = $event->getAuthenticationToken()->getUser(); 
    } 

Попробуйте реализацию этого метода тоже.

У меня есть ваша идентичная конфигурация (security.yml и определение службы), но я не использую fosuserbunde.

надеюсь, что эта помощь

Смежные вопросы