令牌存储不包含身份验证令牌和 denyAccessUnlessGranted()

Token storage contains no authentication token and denyAccessUnlessGranted()

我有一个错误:

"The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

这是由于 denyAccessUnlessGranted() 添加到控制器造成的。它发生在测试环境中,因为有 security: false。在这种情况下是否有处理环境的机制或者我应该如何处理?

跟踪:

0 /backend/vendor/symfony/framework-bundle/Controller/ControllerTrait.php(179): Symfony\Component\Security\Core\Authorization\AuthorizationChecker->isGranted('read', Object(App\Entity\Company))
1 /backend/vendor/symfony/framework-bundle/Controller/ControllerTrait.php(192): Symfony\Bundle\FrameworkBundle\Controller\AbstractController->isGranted('read', Object(App\Entity\Company))
2 /backend/src/Controller/CompanyController.php(125): Symfony\Bundle\FrameworkBundle\Controller\AbstractController->denyAccessUnlessGranted('read', Object(App\Entity\Company))
3 /backend/vendor/symfony/http-kernel/HttpKernel.php(150): App\Controller\CompanyController->cget(Object(Symfony\Component\HttpFoundation\Request), Object(App\Service\CompanyService))
4 /backend/vendor/symfony/http-kernel/HttpKernel.php(67): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
5 /backend/vendor/symfony/http-kernel/Kernel.php(198): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
6 /backend/public/index.php(37): Symfony\Component\HttpKernel\Kernel->handle(Object(Symfony\Component\HttpFoundation\Request))
7 {main}"

为什么需要在测试环境中使用security false。如果您这样做并在您的应用程序中使用 denyAccessUnlessGranted() ,您将得到您提到的结果。要解决此问题,您必须使用 try catch 给您留下 2 个选项,它们都不是一个好选项。

denyAccessUnlessGranted trows 2 种你需要捕获的异常

  • \LogicException
  • AuthenticationCredentialsNotFoundException

这是我提到的两个选项

  1. 你压制异常并让脚本运行当什么都没发生。如果你这样做,你将不会测试你的应用程序安全配置,更糟糕的是,如果你将这段抑制异常的代码带入你的生产环境,一些生产配置错误可能会使你的安全区域不受保护。

  2. 当你捕捉到这个异常时,你抛出了 AccessDeniedException。如果您的应用程序在生产环境中配置不当,这将阻止访问区域,但这样做会使应用程序的这一部分在测试环境中无法访问,我认为您不希望这样。

应用程序的安全组件与其他所有业务功能一样,都是应用程序的一部分。它应该在每个环境中都处于活动状态并且配置相同。您的测试、开发或生产环境之间的唯一区别应该在参数文件中(比如用户存储在哪里)。

希望这对您有所帮助, 亚历山德鲁·科索伊