1. 程式人生 > >xss攻擊問題以及如何防範

xss攻擊問題以及如何防範

htm eth eat 需要 bject quest add 內容 方案

當用戶提交評論的時候,比如如下評論內容

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("添加成功")

xss攻擊問題以及如何防範