Symfony2 登录后成功处理程序不工作

Success handler not working after Symfony2 login

目标是在 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;
    }
}

这是来自 UserBundle 的 services.xml:

<?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 在登录成功后没有被调用。可能是我遗漏了什么?

在我的工作解决方案中,我在我的侦听器中实现了 onSecurityInteractiveLogin 方法:

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

也尝试实施此方法。

我有与您相同的配置(security.yml 和服务定义),但我不使用 fosuserbunde。

希望对您有所帮助