如何使 onAuthenticationSuccess 函数被调用

mlw*_*mos 5 authentication symfony

我想在认证成功后采取一些行动。

我创建了一个扩展 DefaultAuthenticationSuccessHandler 的类,并重新定义了 onAuthenticationSuccess 函数。

尽管身份验证成功,但程序永远不会进入该功能:为什么?


namespace my_name_space;

use   Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Bridge\Monolog\Logger;


class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler {
private $em;
private $logger;

function __construct(Logger $logger, HttpUtils $httpUtils, EntityManager $em) {
    parent::__construct($httpUtils);
    $this->em = $em;
    $this->logger = $logger;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
    $this->logger->info("onAuthenticationSuccess");
    $response = parent::onAuthenticationSuccess($request, $token);
    $token->eraseCredentials();        
    $token->getUser()->addRole('ROLE_USER');

    return $response;
}
Run Code Online (Sandbox Code Playgroud)

}

services:
security.authentication.success.handler:
    class: MY\NAMESPACE\AuthenticationSuccessHandler
    arguments: ["@monolog.logger.php","@security.http_utils", "@doctrine.orm.default_entity_manager"]
Run Code Online (Sandbox Code Playgroud)

安全.yml

form_login:
            check_path: _security_check
            use_referer: true
            use_forward: true
            login_path: my_login
            success_handler: security.authentication.success.handler
Run Code Online (Sandbox Code Playgroud)

Rva*_*aak 5

您可以通过向相关安全标记注册服务来侦听成功登录尝试后触发的事件:

app.login_listener:
    class: AppBundle\EventListener\LoginListener
    arguments:
        - @security.authorization_checker
        - @security.token_storage
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: yourMethod }
Run Code Online (Sandbox Code Playgroud)

其中yourMethod可以包含您要执行的代码。