有一些安全原因,我想阻止访问 twig 中的类常量。我该怎么做?
注意:可以使用下面的代码访问常量。
{{ constant('Entity\\Demo::MY_CONSTANT') }}
有一些安全原因,我想阻止访问 twig 中的类常量。我该怎么做?
注意:可以使用下面的代码访问常量。
{{ constant('Entity\\Demo::MY_CONSTANT') }}
我相信你可以使用沙盒扩展来做到这一点:http: //twig.sensiolabs.org/doc/api.html#sandbox-extension
此扩展允许您定义一个安全策略,该策略基本上具有功能、标签、过滤器的白名单......
您可以全局启用沙盒模式,或者仅对特定包含使用沙盒模式(默认行为):
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
沙盒不是灵丹妙药。因为在系统中用户自己编写模板,这就带来了安全问题。
出于这个原因,在扩展中覆盖函数可能是一个很好的解决方案。
$environment = new Twig_Environment($loader, array('autoescape' => self::$_autoEscapeOpened));
$myTwigExtension = new MyTwigExtension();
//note that MyTwigExtension extends Twig_Extension
$environment->addExtension($myTwigExtension);
//here is MyTwigExtension
class MyTwigExtension extends \Twig_Extension {
//in my twig extension, there is a method called getFunctions. If not, write one.
public function getFunctions() {
$functions = array(
new \Twig_SimpleFunction('constant', array($this, 'constant')),
);
return $functions;
}
//and add the customized constant function in your extension here!
public function constant($variable){
return '';
}
}
如果您不想使用扩展,请参阅http://twig.sensiolabs.org/doc/advanced.html#functions
Ant 结果很好,屏幕没有输出,没有任何沙箱使用。(解决方案在后端)
希望这可以帮助。