简体   繁体   English

如何在控制器中访问防火墙配置?

[英]How to access firewall configuration in controller?

I'm trying to get the firewall information (define in security.yml ) in one of my controller. 我正在尝试在我的一个控制器中获取firewall信息(在security.yml中定义)。

The part I need is the switch_user configuration : 我需要的部分是switch_user配置:

switch_user: { role: ROLE_ADMIN, parameter: _abagnale }

The goal is to create a link in admin section which allows administrators to switch user in one click. 目标是在管理部分创建一个链接,允许管理员一键切换用户。

First test 第一次测试

I have tried to define this values as parameters. 我试图将此值定义为参数。

security:
     # ...
     switch_user: { role: %switch_user_role%, parameter: %switch_user_parameter% }

parameters:
   switch_user_role:      ROLE_ADMIN
   switch_user_parameter: _abagnale

And now in controller, I can get it with $this->container->parameters['switch_user_role'] . 现在在控制器中,我可以使用$this->container->parameters['switch_user_role']来获取它。

This solution is not sufficient, because if I don't want to override default symfony parameters, switch_user_role and switch_user_parameter will not be defined. 此解决方案还不够,因为如果我不想覆盖默认的symfony参数,则不会定义switch_user_roleswitch_user_parameter

Second test 第二次测试

An other way I have tried is to retrieve an object instance that represent the current firewall. 我尝试过的另一种方法是检索代表当前防火墙的对象实例。

I have discovered I can retrieve firewall name in controller with $this->container->get('security.context')->getToken()->getProviderKey() 我发现我可以使用$this->container->get('security.context')->getToken()->getProviderKey()在控制器中检索防火墙名称

But I'm stuck here because I can't find what I have to do with this value. 但是我被困在这里,因为我无法找到与此值有关的内容。

So what is the best way to access firewall configuration in controller ? 那么在控制器中访问防火墙配置的最佳方法是什么?

May be simple read config file security.yml? 可能是简单的读取配置文件security.yml?

UPD :Ok. UPD :好的。

I think use DI is simple way for to complete your task. 我认为使用DI是完成任务的简单方法。 Sorry, my code for Symfony 2.1. 对不起,我的Symfony 2.1代码。 I can't check how it work in 2.3, but i think it don't have global changes for this logic. 我无法检查它在2.3中是如何工作的,但我认为它没有针对这种逻辑进行全局更改。

All authentication events are processed by some listeners. 所有身份验证事件都由一些侦听器处理。 As Example, Symfony\\Component\\Security\\Http\\Firewall namespace. 例如, Symfony\\Component\\Security\\Http\\Firewall命名空间。 For switch_user event it's Symfony\\Component\\Security\\Http\\Firewall\\SwitchUserListener . 对于switch_user事件,它是Symfony\\Component\\Security\\Http\\Firewall\\SwitchUserListener Extend it and be happy. 扩展它并且开心。

Code: 码:

Given security.yml : 鉴于security.yml

firewalls:
    secured_area_2:
        switch_user:
            provider:             ~
            parameter:            _switch_useraaaaa
            role:                 ROLE_ALLOWED_TO_SWITCH

I create my listener. 我创造了我的倾听者。

<?php

namespace Nonlux\TestBundle\Symfony;

use Symfony\Component\Security\Http\Firewall\SwitchUserListener as BaseListener;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Psr\Log\LoggerInterface;

class SwitchUserListener extends BaseListener
{
    private $usernameParameter;
    private $role;

    public function __construct(SecurityContextInterface $securityContext, UserProviderInterface $provider, UserCheckerInterface $userChecker, $providerKey, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, $usernameParameter = '_switch_user', $role = 'ROLE_ALLOWED_TO_SWITCH', EventDispatcherInterface $dispatcher = null)
    {
        $this->usernameParameter = $usernameParameter;
        $this->role = $role;
        parent::__construct($securityContext, $provider,$userChecker, $providerKey, $accessDecisionManager, $logger, $usernameParameter, $role, $dispatcher);

    }

    public function getUsernameParameter(){
        return $this->usernameParameter;
    }

    public function getRole(){
        return $this->role;
    }
}

I change standart listener with my. 我改变了标准听众。

# app/config/config.yml
imports:
...
    - { resource: services.xml }    
...

Important! 重要! By default security authentication listeners have public = "false" parameter. 默认情况下,安全验证侦听器具有public = "false"参数。 But we don't do it and than we can see child listeners in container. 但我们不这样做,而且我们可以在容器中看到儿童听众。 If you don't like to do it. 如果你不喜欢这样做。 you can create service that can store needed data, fill it from your listener and do your magic. 你可以创建可以存储所需数据的服务,从你的听众那里填充它并发挥你的魔力。

<!-- app/config/services.xml  -->
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">  
    <parameters>
        <parameter key="nonlux.security.authentication.switchuser_listener.class">Nonlux\TestBundle\Symfony\SwitchUserListener</parameter>
    </parameters>
    <services>
        <service id="security.authentication.switchuser_listener" class="%nonlux.security.authentication.switchuser_listener.class%" abstract="true">
            <tag name="monolog.logger" channel="security" />
            <argument type="service" id="security.context" />
            <argument /> <!-- User Provider -->
            <argument type="service" id="security.user_checker" />
            <argument /> <!--  Provider Key -->
            <argument type="service" id="security.access.decision_manager" />
            <argument type="service" id="logger" on-invalid="null" />
            <argument>_switch_user</argument>
            <argument>ROLE_ALLOWED_TO_SWITCH</argument>
            <argument type="service" id="event_dispatcher" on-invalid="null"/>
        </service>
    </services>
</container>

Use it in controler ( use service 'security.authentication.switchuser_listener.you_firewall_name') 在控制器中使用它(使用服务'security.authentication.switchuser_listener.you_firewall_name')

<?php

namespace Nonlux\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{

   /**
     * @Route("/switch", name="switch")
     * @Template()
     */
    public function switchAction()
    {
        $name=$this->get("security.authentication.switchuser_listener.secured_area_2")->getUsernameParameter();
        return array('name' => $name);
    }
}

See magic in page and be happy. 在页面中看到魔法,并开心。

Hello  _switch_useraaaaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM