好吧,在挖掘捆绑包的代码后,我弄清楚了。问题是由Symfony的HTTP基本身份验证影响来处理不良凭证的方式。这 401 Bad Credentials
响应是由自定义响应创建的 BasicAuthenticationEntryPoint
, ,这是由 BasicAuthenticationListener
' handle
功能,立即在 AuthenticationException
已抛出相同的功能。因此,听众无法与听众一起捕捉这个例外:
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (false === $username = $request->headers->get('PHP_AUTH_USER', false)) {
return;
}
if (null !== $token = $this->securityContext->getToken()) {
if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) {
return;
}
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Basic Authentication Authorization header found for user "%s"', $username));
}
try {
$token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey));
$this->securityContext->setToken($token);
} catch (AuthenticationException $failed) {
$this->securityContext->setToken(null);
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage()));
}
if ($this->ignoreFailure) {
return;
}
$event->setResponse($this->authenticationEntryPoint->start($request, $failed));
}
}
入口点的 start
函数创建自定义响应,但涉及不例外:
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
$response->setStatusCode(401, $authException ? $authException->getMessage() : null);
return $response;
}
拳头 if
- 在 handle
上面的函数还解释了为什么在“根本没有用户凭据”的情况下起作用,因为在这种情况下,听众只是停止尝试对用户进行身份验证,因此Symfony的防火墙听众会抛出一个例外(不确定在哪里确实),所以Fosrestbundle AccessDeniedListener
能够抓住 AuthenticationException
并做事。