簡體   English   中英

如何從 Symfony 5 中的請求中獲取防火牆名稱?

[英]How to get firewall name from Request in Symfony 5?

問題很簡單。 我正在實施AccessDeniedListener ,我得到一個ExceptionEvent object。 從這里我可以得到請求。 僅當我位於 security.yaml 中定義的防火牆之一時,我才想應用某些邏輯。

如何從ExceptionEventRequest實例中獲取防火牆名稱?

編輯:我發現這段代碼“有效”

$firewall_context_name = $event->getRequest()->attributes->get('_firewall_context');

但是我對此不太高興。 應該有一個可以以某種方式檢索的FirewallContextFirewallConfig對象,不是嗎? 謝謝

class AccessDeniedListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            // the priority must be greater than the Security HTTP
            // ExceptionListener, to make sure it's called before
            // the default exception listener
            KernelEvents::EXCEPTION => ['onKernelException', 2],
        ];
    }
    
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();
        if (!$exception instanceof AccessDeniedException) {
            return;
        }
        
        $request = $event->getRequest();

        // HOW TO GET FIREWALL NAME HERE???

安全性.yaml

   firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        api:
            pattern: ^/api/
            security: false
        main:
            custom_authenticators:
                - App\Security\LoginFormAuthenticator
            logout:
                path: app_logout
            lazy: true
            provider: app_user_provider

您鏈接的文檔中所述:

這個 object 可以通過Symfony\Bundle\SecurityBundle\Security\FirewallMap class 的getFirewallConfig(Request $request)方法訪問

此 class 無法直接注入,因此您必須在services.yaml中配置您的依賴項,使用服務別名security.firewall.map (或者如果您計划在其他地方使用它)。

services:
  # ...
  App\Listener\AccessDeniedListener:
    arguments:
      $firewallMap: '@security.firewall.map'

現在修改您的偵聽器以接收此參數:

class AccessDeniedListener implements EventSubscriberInterface
{
    private $firewallMap;

    public function __construct(FirewallMapInterface $firewallMap)
    {
        $this->firewallMap = $firewallMap;
    }

    // Ommited getSubscribedEvents
    
    public function onKernelException(ExceptionEvent $event): void
    {
        $request = $event->getRequest();

        $firewallConfig = $this->firewallMap->getFirewallConfig($request);

        if (null === $firewallConfig) {
            return;
        }
        $firewallName = $firewallConfig->getName();
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM