使用TWIG Markdown转义HTML代码 [英] Escape HTML code with TWIG Markdown
问题描述
我正在研究博客评论包,我想让用户使用Markdown发布一些代码.
我正在使用symfony2,TWIG和 KNPMarkdownBundle 进行解析
I am working on a blog comment bundle and I would like to let user post some code using Markdown.
I am working with symfony2, TWIG and KNPMarkdownBundle for parsing
{{ post.content|markdown }}
实际上,对内容进行了降价分析(<code>
<p>
...),但是如果我的内容中包含一些HTML代码,例如:
Actually, the content is well markdown parsed (<code>
<p>
...) but if I have some HTML code in my content like :
Some content
``` <script>alert("hello world");</script> ```
代码未转义,并且我有一条警告消息.
请有人可以解释我该如何处理XSS问题? (foo|raw
和foo|escape
正在中断解析)
The code is not escaped and I have a alert message.
Please can someone explain how can I deal with XSS issues ? (foo|raw
and foo|escape
are breaking parsing)
推荐答案
我只是碰到了这个问题,但是由于strip_tags
不足以保护attributes标记中的值,因此我将提交答案.
I just happened to have this problem, but since strip_tags
is not enough to protect values in the attributes tag, I will submit my answer.
我正在使用 HTML净化器删除所有不需要的HTML元素和属性.打开命令控制台并执行以下命令进行安装.
I'm using HTML Purifier to remove all unwanted HTML elements and attributes. Open a command console and execute the following command to install it.
$ composer require ezyang/htmlpurifier "^4.6"
然后,您可以创建自己的Twig扩展名:
Then you can create your own Twig extension:
namespace AcmeBundle\Twig;
class HTMLPurifierExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('html_purifier', array($this, 'purify'), array('is_safe' => array('html'))),
);
}
public function purify($text)
{
$elements = array(
'p',
'br',
'small',
'strong', 'b',
'em', 'i',
'strike',
'sub', 'sup',
'ins', 'del',
'ol', 'ul', 'li',
'h1', 'h2', 'h3',
'dl', 'dd', 'dt',
'pre', 'code', 'samp', 'kbd',
'q', 'blockquote', 'abbr', 'cite',
'table', 'thead', 'tbody', 'th', 'tr', 'td',
'a[href|target|rel|id]',
'img[src|title|alt|width|height|style]'
);
$config = \HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', implode(',', $elements));
$purifier = new \HTMLPurifier($config);
return $purifier->purify($text);
}
public function getName()
{
return 'html_purifier';
}
}
打开services.yml
并将扩展注册为服务:
Open services.yml
and register the extension as a service:
services:
acme.html_purifier_extension:
class: AcmeBundle\Twig\HTMLPurifierExtension
public: false
tags:
- { name: twig.extension }
现在您可以将其与
{{ post.content|markdown|html_purifier }}
这篇关于使用TWIG Markdown转义HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!