【发布时间】:2017-05-14 22:24:50
【问题描述】:
我听说过过滤器|safe,但如果我理解正确的话,那是不安全的,并且会为注入创建一个后门。
用格式化文本显示完整帖子的替代方法是什么?
【问题讨论】:
标签: python django django-templates django-ckeditor
我听说过过滤器|safe,但如果我理解正确的话,那是不安全的,并且会为注入创建一个后门。
用格式化文本显示完整帖子的替代方法是什么?
【问题讨论】:
标签: python django django-templates django-ckeditor
我认为当您不使用|safe 的过滤器时,输出应该只返回带有html 标记的文本(不呈现为html 输出)。
但是,如果你需要排除一些危险的标签比如<script>location.reload()</script>,你需要使用自定义的模板标签过滤器来处理它..
我得到了很好的答复:https://stackoverflow.com/a/699483/6396981,通过BeautifulSoup。
from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape
register = template.Library()
INVALID_TAGS = ['script',]
def clean_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name in INVALID_TAGS:
# tag.hidden = True # you also can use this.
tag.replaceWith(escape(tag))
return soup.renderContents()
# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>')
# output:
# <html><body><h1>This is heading</h1> and this one is xss injection <script>location.reload()</script></body></html>
@register.filter
def safe_exclude(text):
# eg: {{ post.description|safe_exclude|safe }}
return clean_html(text)
希望有用..
【讨论】: