[英]How to get firewall name from Request in Symfony 5?
The question is simple.问题很简单。 I am implmenting
AccessDeniedListener
and I get an ExceptionEvent
object.我正在实施
AccessDeniedListener
,我得到一个ExceptionEvent
object。 From this I can get request.从这里我可以得到请求。 I want to apply certain logic ONLY if I am inside one of my firewalls defined in security.yaml.
仅当我位于 security.yaml 中定义的防火墙之一时,我才想应用某些逻辑。
How can I get the Firewall name from ExceptionEvent
or Request
instances?如何从
ExceptionEvent
或Request
实例中获取防火墙名称?
EDIT: I have found this code "works"编辑:我发现这段代码“有效”
$firewall_context_name = $event->getRequest()->attributes->get('_firewall_context');
However Im not very happy about it.但是我对此不太高兴。 There should be a
FirewallContext
or FirewallConfig
objects retrieveable somehow, no? 应该有一个可以以某种方式检索的
FirewallContext
或FirewallConfig
对象,不是吗? Thanks谢谢
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???
security.yaml安全性.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
As stated in the docs you linked :如您链接的文档中所述:
This object can be accessed through the
getFirewallConfig(Request $request)
method of theSymfony\Bundle\SecurityBundle\Security\FirewallMap
class这个 object 可以通过
Symfony\Bundle\SecurityBundle\Security\FirewallMap
class 的getFirewallConfig(Request $request)
方法访问
This class cannot be injected directly, so you'll have to configure your dependency in services.yaml
using the service alias security.firewall.map
(or create a service alias if you plan to use it somewhere else).此 class 无法直接注入,因此您必须在
services.yaml
中配置您的依赖项,使用服务别名security.firewall.map
(或者如果您计划在其他地方使用它)。
services:
# ...
App\Listener\AccessDeniedListener:
arguments:
$firewallMap: '@security.firewall.map'
Now modify your listener to receive this parameter:现在修改您的侦听器以接收此参数:
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.