我正在使用Symfony2,需要将失败的登录尝试保存到数据库。
我认为我应该使用以下方法:
// Symfony/Component/Security/Http/Autentication/AbstractAuthenticationListener.php
onFailure()
onSuccess()
但我不确定如何从内部访问数据库连接。
如何从这些函数中运行数据库插入?
答案 0 :(得分:2)
您需要在security.yml
中定义自己的失败处理程序 form_login:
provider: fos_userbundle
login_path: /user/login
csrf_provider: form.csrf_provider
failure_handler: myBundle.login.failure
创建处理失败的服务
bundle.login.failure:
class: 'MyBundle\Services\AuthenticationFailureHandler'
arguments: ['@kernel']
然后构建你的失败处理程序:
<?php
namespace MyBundle\Services;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler
{
public function __construct(HttpKernelInterface $httpKernel)
{
$this->httpKernel = $httpKernel;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
// the auth just failed :-(
}
}
要保存对数据库的尝试,请将您的Doctrine管理器注入服务,并在onFail方法中保留该尝试。
答案 1 :(得分:0)
只是为了记录,使用security.authentication.failure
侦听器是一种简单的方法。见Symfony documentation。您可以使用this blog post来了解如何将日志保存到实际数据库。
namespace AppBundle\EventListener;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
class AuthenticationFailureListener implements LoggerAwareInterface
{
use LoggerAwareTrait;
public function onFailure(AuthenticationFailureEvent $event)
{
$token = $event->getAuthenticationToken();
$username = $token->getUsername();
$this->logger->info('Authentication failed', ['username' => $username]);
}
}
并在services.yml
app.authentication_failure_listener:
class: AppBundle\EventListener\AuthenticationFailureListener
calls:
- [setLogger, ['@logger']]
tags:
- { name: monolog.logger, channel: security }
- { name: kernel.event_listener, event: security.authentication.failure, method: onFailure }