我的问题
我应该返回什么样的响应才能不改变默认响应?或者,有没有更好的方法将记录器添加到登录失败/badcredentialsexception?
我找到了这个帖子
here
它声明您可以(在Symfony 2.4中)自定义身份验证失败或成功,如下所示:
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CustomTimeAuthenticator extends TimeAuthenticator implements AuthenticationFailureHandlerInterface, AuthenticationSuccessHandlerInterface
{
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
error_log('You are out!');
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
error_log(sprintf('Yep, you are in "%s"!', $token->getUsername()));
}
}
它还说
…还可以通过返回
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($exception->getCode()) {
return new Response('Not the right time to log in, come back later.');
}
}
不幸的是,它似乎在Symfony 4
you have to return a Response
(与上面的2.4代码不同)因此我的代码是:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Psr\Log\LoggerInterface;
class LoginFailureLogger implements AuthenticationFailureHandlerInterface
{
private $logger;
private $security;
public function __construct(TokenStorageInterface $security, LoggerInterface $logger)
{
$this->logger = $logger;
$this->security = $security;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$user = $exception->getToken()->getUser();
$this->logger->notice('Failed to login user: "'. $user. '"". Reason: '. $exception->getMessage());
}
}
但当页面运行时,我得到: