![](/img/trans.png)
[英]Symfony: Retrieve user from a different firewall than the firewall being used in the current request
[英]How to get firewall name from Request in Symfony 5?
問題很簡單。 我正在實施AccessDeniedListener
,我得到一個ExceptionEvent
object。 從這里我可以得到請求。 僅當我位於 security.yaml 中定義的防火牆之一時,我才想應用某些邏輯。
如何從ExceptionEvent
或Request
實例中獲取防火牆名稱?
編輯:我發現這段代碼“有效”
$firewall_context_name = $event->getRequest()->attributes->get('_firewall_context');
但是我對此不太高興。 應該有一個可以以某種方式檢索的FirewallContext
或FirewallConfig
對象,不是嗎? 謝謝
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.