![](/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.