我想从控制器内部检查它是否是一个安全的页面.
这该怎么做 ?

我的用例如下:

>用户可以注册并登录
>如果他登录并尝试访问受保护的页面,他将被重定向到“测试版”页面,直到6月底.
>如果他试图访问普通页面(不安全),他将能够访问它而无需任何重定向.

谢谢你的帮助 !

斯坦

当Symfony2处理请求时,它与url模式匹配app / config / security.yml中定义的每个防火墙.当url模式与防火墙模式匹配时,Symfony2会创建一些侦听器对象并调用这些对象的handle方法.如果任何侦听器返回一个Response对象,则循环中断,Symfony2输出响应.身份验证部分在身份验证侦听器中完成.它们是从匹配防火墙中定义的配置创建的,例如form_login,http_basic等.如果用户未经过身份验证,则经过身份验证的侦听器会创建一个RedirectResponse对象,以将用户重定向到登录页面.对于您的情况,您可以通过创建自定义身份验证侦听器并将其添加到安全页面防火墙中来作弊.示例实现如下,

创建令牌类,

namespace Your\Namespace;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;

class MyToken extends AbstractToken
{
    public function __construct(array $roles = array())
    {
        parent::__construct($roles);
    }

    public function getCredentials()
    {
        return '';
    }
}

创建一个实现AuthenticationProviderInterface的类.对于form_login侦听器,它使用给定的UserProvider进行身份验证.在这种情况下,它什么都不做.

namespace Your\Namespace;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Acme\BaseBundle\Firewall\MyToken;

class MyAuthProvider implements AuthenticationProviderInterface
{

    public function authenticate(TokenInterface $token)
    {
        if (!$this->supports($token)) {
            return null;
        }

        throw new \Exception('you should not get here');
    }

    public function supports(TokenInterface $token)
    {
        return $token instanceof MyToken;
    }

创建入口点类.侦听器将从此类创建RedirectResponse.

namespace Your\Namespace;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\HttpUtils;


class MyAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    private $httpUtils;
    private $redirectPath;

    public function __construct(HttpUtils $httpUtils,$redirectPath)
    {
        $this->httpUtils = $httpUtils;
        $this->redirectPath = $redirectPath;
    }

    /**
     * {@inheritdoc}
     */
    public function start(Request $request,AuthenticationException $authException = null)
    {
        //redirect action goes here
        return $this->httpUtils->createRedirectResponse($request,$this->redirectPath);
    }

创建一个监听器类.在这里,您将实现重定向逻辑.

namespace Your\Namespace;

use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;

class MyAuthenticationListener implements ListenerInterface
{
    private $securityContext;
    private $authenticationEntryPoint;


    public function __construct(SecurityContextInterface $securityContext,AuthenticationEntryPointInterface $authenticationEntryPoint)
    {
        $this->securityContext = $securityContext;
        $this->authenticationEntryPoint = $authenticationEntryPoint;
    }

    public function handle(GetResponseEvent $event)
    {
        $token = $this->securityContext->getToken();
        $request = $event->getRequest();
        if($token === null){
            return;
        }

        //add your logic
        $redirect = // boolean value based on your logic

        if($token->isAuthenticated() && $redirect){

            $response = $this->authenticationEntryPoint->start($request);
            $event->setResponse($response);
            return;
        }
    }

}

创建服务.

<?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">

    <services>

        <service id="my_firewall.security.authentication.listener"
                 class="Your\Namespace\MyAuthenticationListener"
                 parent="security.authentication.listener.abstract"
                 abstract="true">
            <argument type="service" id="security.context" />
            <argument /> <!-- Entry Point -->
        </service>

        <service id="my_firewall.entry_point" class="Your\Namespace\MyAuthenticationEntryPoint" public="false" ></service>

        <service id="my_firewall.auth_provider" class="Your\Namespace\MyAuthProvider" public="false"></service>
    </services>

</container>

注册听众.在捆绑包DependencyInjection文件夹中创建名为Security / Factory的文件夹.然后创建工厂类.

namespace Your\Bundle\DependencyInjection\Security\Factory;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DeFinitionDecorator;
use Symfony\Component\DependencyInjection\DeFinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\DeFinition\Builder\NodeDeFinition;

class MyFirewallFactory implements SecurityFactoryInterface
{

    public function create(ContainerBuilder $container,$id,$config,$userProvider,$defaultEntryPoint)
    {
        $provider = 'my_firewall.auth_provider.'.$id;
        $container->setDeFinition($provider,new DeFinitionDecorator('my_firewall.auth_provider'));

        // entry point
        $entryPointId = $this->createEntryPoint($container,$defaultEntryPoint);

        // listener
        $listenerId = 'my_firewall.security.authentication.listener'.$id;
        $listener = $container->setDeFinition($listenerId,new DeFinitionDecorator('my_firewall.security.authentication.listener'));
        $listener->replaceArgument(1,new Reference($entryPointId));
        return array($provider,$listenerId,$entryPointId);
    }

    public function getPosition()
    {
        return 'pre_auth';
    }

    public function getKey()
    {
        return 'my_firewall'; //the listener name
    }

    protected function getListenerId()
    {
        return 'my_firewall.security.authentication.listener';
    }

    public function addConfiguration(NodeDeFinition $node)
    {
        $node
            ->children()
                ->scalarNode('redirect_path')->end()
            ->end()
            ;
    }

    protected function createEntryPoint($container,$defaultEntryPointId)
    {
        $entryPointId = 'my_firewall.entry_point'.$id;
        $container
            ->setDeFinition($entryPointId,new DeFinitionDecorator('my_firewall.entry_point'))
            ->addArgument(new Reference('security.http_utils'))
            ->addArgument($config['redirect_path'])
            ;
        return $entryPointId;
    }

}

然后在bundle文件夹的NamespaceBundle.PHP中添加以下代码.

public function build(ContainerBuilder $builder){
    parent::build($builder);
    $extension = $builder->getExtension('security');
    $extension->addSecurityListenerFactory(new Security\Factory\MyFirewallFactory());
}

身份验证监听器已创建,phew :).现在在app / config / security.yml中执行以下操作.

api_area:
  pattern: ^/secured/
  provider: fos_userbundle
  form_login:
    check_path: /login_check
    login_path: /login
    csrf_provider: form.csrf_provider
  my_firewall:
    redirect_path: /beta
  logout: true
  anonymous: true

php – Symfony2:如何检查某个操作是否安全?的更多相关文章

  1. Swift获取命名空间(namespace),动态加载类

    1.tips1.1在swift中,类名的组成格式是namespace.类名.比如我们在任意一个控制器的viewDidLoad()方法中打印self,打印结果是:打印结果.png1.2.namespace默认是项目名称,同一个命名空间全局共享2.怎么查看namespacenamespace在info.plist对应的是CFBundleExecutable,我们可以在info.plist中任意右击一行

  2. android – 如何实现消息读取状态,如whatsapp蓝色刻度?

    我正在开发一个应用程序,聊天是一个模块,聊天我正在使用xmpp.当我发送消息时,我使用DeliveryReceiptManager获取该消息传递状态.但我需要表明该消息是用户READ或NOTwhatsApp蓝色tickmark,任何人都可以帮助我,我被击中了.如何实现此消息读取概念.提前致谢.解决方法创建自定义数据包扩展类当进入聊天列表时发送具有相同包ID的消息标签其中mConnection是xm

  3. Symfony2联合查询实现方法

    这篇文章主要介绍了Symfony2联合查询实现方法,结合实例形式简单分析了Symfony2联合查询的具体步骤与实现技巧,需要的朋友可以参考下

  4. 基于JavaScript 下namespace 功能的简单分析

    前些天在剥离 百度随心听 的播放器引擎时,看到了一个namespace方法,觉得新奇,当然只是对于我自己而言,我入门js不久,经验尚浅

  5. Symfony2实现在controller中获取url的方法

    这篇文章主要介绍了Symfony2实现在controller中获取url的方法,实例分析了Symfony获取URL的常用方法与使用技巧,需要的朋友可以参考下

  6. PHP命令空间namespace及use的用法小结

    命名空间一个最明确的目的就是解决重名问题,PHP中不允许两个函数或者类出现相同的名字,否则会产生一个致命的错误。这篇文章主要介绍了PHP命令空间namespace及use的用法实践总结,需要的朋友可以参考下

  7. Symfony2框架学习笔记之HTTP Cache用法详解

    这篇文章主要介绍了Symfony2框架HTTP Cache用法,结合实例形式分析了Symfony框架HTTP缓存的相关使用技巧,需要的朋友可以参考下

  8. Symfony2开发之控制器用法实例分析

    这篇文章主要介绍了Symfony2开发之控制器用法,结合实例形式分析了Symfony2控制器的简单使用技巧,需要的朋友可以参考下

  9. Symfony2在Nginx下的配置方法图文教程

    这篇文章主要介绍了Symfony2在Nginx下的配置方法,结合图文形式较为详细的分析了Symfony2在Nginx下的配置方法与具体操作步骤,需要的朋友可以参考下

  10. php中namespace及use用法分析

    这篇文章主要介绍了php中namespace及use用法,结合实例形式分析了php中namespace及use的功能与具体使用方法,需要的朋友可以参考下

随机推荐

  1. PHP个人网站架设连环讲(一)

    先下一个OmnihttpdProffesinalV2.06,装上就有PHP4beta3可以用了。PHP4给我们带来一个简单的方法,就是使用SESSION(会话)级变量。但是如果不是PHP4又该怎么办?我们可以假设某人在15分钟以内对你的网页的请求都不属于一个新的人次,这样你可以做个计数的过程存在INC里,在每一个页面引用,访客第一次进入时将访问时间送到cookie里。以后每个页面被访问时都检查cookie上次访问时间值。

  2. PHP函数学习之PHP函数点评

    PHP函数使用说明,应用举例,精简点评,希望对您学习php有所帮助

  3. ecshop2.7.3 在php5.4下的各种错误问题处理

    将方法内的函数,分拆为2个部分。这个和gd库没有一点关系,是ecshop程序的问题。会出现这种问题,不外乎就是当前会员的session或者程序对cookie的处理存在漏洞。进过本地测试,includes\modules\integrates\ecshop.php这个整合自身会员的类中没有重写integrate.php中的check_cookie()方法导致,验证cookie时返回的username为空,丢失了登录状态,在ecshop.php中重写了此方法就可以了。把他加到ecshop.php的最后面去就可

  4. NT IIS下用ODBC连接数据库

    $connection=intodbc_connect建立数据库连接,$query_string="查询记录的条件"如:$query_string="select*fromtable"用$cur=intodbc_exec检索数据库,将记录集放入$cur变量中。再用while{$var1=odbc_result;$var2=odbc_result;...}读取odbc_exec()返回的数据集$cur。最后是odbc_close关闭数据库的连接。odbc_result()函数是取当前记录的指定字段值。

  5. PHP使用JpGraph绘制折线图操作示例【附源码下载】

    这篇文章主要介绍了PHP使用JpGraph绘制折线图操作,结合实例形式分析了php使用JpGraph的相关操作技巧与注意事项,并附带源码供读者下载参考,需要的朋友可以参考下

  6. zen_cart实现支付前生成订单的方法

    这篇文章主要介绍了zen_cart实现支付前生成订单的方法,结合实例形式详细分析了zen_cart支付前生成订单的具体步骤与相关实现技巧,需要的朋友可以参考下

  7. Thinkphp5框架实现获取数据库数据到视图的方法

    这篇文章主要介绍了Thinkphp5框架实现获取数据库数据到视图的方法,涉及thinkPHP5数据库配置、读取、模型操作及视图调用相关操作技巧,需要的朋友可以参考下

  8. PHP+jquery+CSS制作头像登录窗(仿QQ登陆)

    本篇文章介绍了PHP结合jQ和CSS制作头像登录窗(仿QQ登陆),实现了类似QQ的登陆界面,很有参考价值,有需要的朋友可以了解一下。

  9. 基于win2003虚拟机中apache服务器的访问

    下面小编就为大家带来一篇基于win2003虚拟机中apache服务器的访问。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. Yii2中组件的注册与创建方法

    这篇文章主要介绍了Yii2之组件的注册与创建的实现方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

返回
顶部