xss攻击问题以及如何防范

当用户提交评论的时候,比如如下评论内容

111 <scripy>alert(111);</scripy>

这样当现实评论的时候会先弹出111弹框,再显示评论。这就是xss攻击。

所以,我们需要对评论内容进行检测,对恶意代码进行删除,不让不存到数据库。

如下解决方案:

def add_article(request):

    if request.method=="POST":
        title=request.POST.get('title')
        article_content=request.POST.get('article_content')  # 获取评论内容
        user=request.user
        # 使用BeautifulSoup模块
        from bs4 import BeautifulSoup
        # 
        bs=BeautifulSoup(article_content,"html.parser")
        desc=bs.text[0:150]+"..."

        # 过滤非法标签,会寻找到这个页面的所有标签
        for tag in bs.find_all():
            
            print(tag.name)
            # 如果有非法标签
            if tag.name in ["script", "link"]:
# 使用decompose()删除非法标签 tag.decompose() article_obj
=models.Article.objects.create(user=user,title=title,desc=desc) models.ArticleDetail.objects.create(content=str(bs),article=article_obj) return HttpResponse("添加成功")

 

posted @ 2018-09-30 21:51  aaronthon  阅读(449)  评论(0编辑  收藏  举报