我的问题
我需要返回什么样的响应才不会改变默认响应? 或者有更好的方法来追踪登录失败/坏凭据异常?
详情
我在这个帖子中找到了答案(链接),它说明您可以(在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()));
}
}
它还指出,您可以通过返回一个 Response 实例来完全绕过默认行为:
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中必须返回一个响应(与上述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());
}
}
但是当页面运行时,我遇到了:
身份验证失败处理程序没有返回响应。