使用 PreAuthentication 时覆盖自定义异常

Custom exception overriden when using PreAuthentication

我正在学习 How to Authenticate Users with API Keys 教程。

当我输入正确的 API 密钥时,一切正常。另一方面,当 API 键不正确或丢失时,代码应该抛出异常(例如第一种情况下的 BadCredentialsException)。然而,这个异常似乎被覆盖了,最终的请求响应是由 Symfony AccessListener.php 抛出的 AuthenticationCredentialsNotFoundException。 我收到错误:

A Token was not found in the SecurityContext.

这让我认为 PreAuthenticator 中抛出的异常以某种方式被丢弃,安全机制只是进一步抱怨它找不到令牌(这确实是正常的,因为提供的 API 密钥不正确) .

如果这是预期的行为(我觉得很难过),那么在文档中提出使用异常的 PreAuthenticator 是没有意义的...

为了解决这个问题,我创建了一个自定义身份验证提供程序,它工作正常!

教程:http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html