目錄
- Honeypot的工作原理
- Django中如何實(shí)現(xiàn)表單honeypot驗(yàn)證?
- 編寫(xiě)模板標(biāo)簽
- 編寫(xiě)裝飾器
- 參考
如果你的網(wǎng)站中允許匿名用戶(hù)通過(guò)POST方式提交表單, 比如用戶(hù)注冊(cè)表, 評(píng)論表或者留下用戶(hù)聯(lián)系方式的表單,你一定要防止機(jī)器人或爬蟲(chóng)程序惡意提交大量的垃圾數(shù)據(jù)到你的數(shù)據(jù)庫(kù)中。這種情況不是可能會(huì)發(fā)生,而是一定會(huì)發(fā)生。一種解決這種問(wèn)題的方式就是在表單中加入人機(jī)交互驗(yàn)證碼(CAPTCHA), 另一種方式就是在表單中加入honeypot隱藏字段,然后在視圖中對(duì)隱藏字段的值進(jìn)行驗(yàn)證。兩種驗(yàn)證方式的目的都是一樣,防止機(jī)器人或程序通過(guò)偽裝成人來(lái)提交數(shù)據(jù)。今天我們就來(lái)詳細(xì)介紹下如何在表單中添加honeypot增加安全性。
Honeypot的工作原理
Honeypot又名蜜罐,其實(shí)本質(zhì)上是種陷阱。我們?cè)诒韱沃泄室馔ㄟ^(guò)CSS隱藏一些字段, 這些字段一般人是不可見(jiàn)的。然而機(jī)器人或程序會(huì)以為這些字段也是必需的字段(required), 所以會(huì)補(bǔ)全后提交表單,這就中了我們的陷阱。在視圖中我們可以通過(guò)裝飾器對(duì)用戶(hù)提交的表單數(shù)據(jù)進(jìn)行判斷,來(lái)驗(yàn)證表單的合法性。比如honeypot字段本來(lái)應(yīng)該為空的,現(xiàn)在居然有內(nèi)容了,顯然這是機(jī)器人或程序提交的數(shù)據(jù),我們可以拒絕其請(qǐng)求。
Django中如何實(shí)現(xiàn)表單honeypot驗(yàn)證?
Django表單中添加honeypot,一共分兩步:
1. 編寫(xiě)模板標(biāo)簽(templatetags),在包含模板的表單中生成honeypot字段。
2. 編寫(xiě)裝飾器(decorators.py), 對(duì)POST請(qǐng)求發(fā)送來(lái)的表單數(shù)據(jù)進(jìn)行驗(yàn)證。
由于honeypot的功能所有app都可以用到,我們創(chuàng)建了一個(gè)叫common的app。整個(gè)項(xiàng)目的目錄結(jié)構(gòu)如下所示。只有標(biāo)藍(lán)色的4個(gè)文件,是與honeypot相關(guān)的。
![](http://img.jbzj.com/file_images/article/202105/202156145440548.png?202146145447)
編寫(xiě)模板標(biāo)簽
我們?cè)赾ommon目錄下新建templatetags目錄(包含一個(gè)空的__init__.py),然后在新建common_tags_filters.py, 添加如下代碼。
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = template.Library()
# used to render honeypot field
@register.inclusion_tag('common/snippets/honeypot_field.html')
def render_honeypot_field(field_name=None):
"""
Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME).
"""
if not field_name:
field_name = getattr(settings, 'HONEYPOT_FIELD_NAME', 'name1')
value = getattr(settings, 'HONEYPOT_VALUE', '')
if callable(value):
value = value()
return {'fieldname': field_name, 'value': value}
我們現(xiàn)在來(lái)看下上面這段代碼如何工作的。我們創(chuàng)建了一個(gè)名為render_honeypot_field的模板標(biāo)簽,用于在模板中生成honeypot字段。honeypot字段名是settings.py里HONEYPOT_FIELD_NAME,如果沒(méi)有此項(xiàng)設(shè)置,默認(rèn)值為name1。honeypot字段的默認(rèn)值是HONEYPOT_VALUE, 如果沒(méi)有此項(xiàng)設(shè)置,默認(rèn)值為空字符串''。然后這個(gè)函數(shù)將fieldname和value傳遞給如下模板片段。
# common/snippets/honeypot_field.html
div class="form-control" style="display: none;">
label>input type="text" name="{{ fieldname }}" value="{{ value }}" />
/label>
/div>
在Django模板的表單中生成honeypot字段只需按如下操作:
{% load common_tags_filters %}
{% load static %}
form method="post" action="">
{% csrf_token %}
{% render_honeypot_field %}
{% form.as_p %}
/form>
編寫(xiě)裝飾器
在common文件下新建decorators.py, 添加如下代碼。我們編寫(xiě)了check_honeypot和honeypot_exempt兩個(gè)裝飾器,前者給需要對(duì)honeypot字段進(jìn)行驗(yàn)證的視圖函數(shù)使用,后者給不需要對(duì)honeypot字段進(jìn)行驗(yàn)證的視圖函數(shù)使用。
#common/decorators.py
from functools import wraps
from django.conf import settings
from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseRedirect
from django.template.loader import render_to_string
from django.contrib.auth.decorators import user_passes_test
def honeypot_equals(val):
"""
Default verifier used if HONEYPOT_VERIFIER is not specified.
Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable.
"""
expected = getattr(settings, 'HONEYPOT_VALUE', '')
if callable(expected):
expected = expected()
return val == expected
def verify_honeypot_value(request, field_name):
"""
Verify that request.POST[field_name] is a valid honeypot.
Ensures that the field exists and passes verification according to
HONEYPOT_VERIFIER.
"""
verifier = getattr(settings, 'HONEYPOT_VERIFIER', honeypot_equals)
if request.method == 'POST':
field = field_name or settings.HONEYPOT_FIELD_NAME
if field not in request.POST or not verifier(request.POST[field]):
response = render_to_string('common/snippets/honeypot_error.html',
{'fieldname': field})
return HttpResponseBadRequest(response)
def check_honeypot(func=None, field_name=None):
"""
Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified.
"""
# hack to reverse arguments if called with str param
if isinstance(func, str):
func, field_name = field_name, func
def wrapper(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = verify_honeypot_value(request, field_name)
if response:
return response
else:
return func(request, *args, **kwargs)
return inner
if func is None:
def decorator(func):
return wrapper(func)
return decorator
return wrapper(func)
def honeypot_exempt(func):
"""
Mark view as exempt from honeypot validation
"""
# borrowing liberally from django's csrf_exempt
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.honeypot_exempt = True
return wrapper
上面代碼最重要的就是verify_honeypot_value函數(shù)了。如果用戶(hù)通過(guò)POST方式提交的表單里沒(méi)有honeypot字段或該字段的值不等于settings.py中的默認(rèn)值,則驗(yàn)證失敗并返回如下錯(cuò)誤:
# common/snippets/honeypot_error.html
!DOCTYPE html>
html lang="en">
body>
h1>400 Bad POST Request/h1>
p>We have detected a suspicious request. Your request is aborted./p>
/body>
/html>
定義好裝飾器后,我們對(duì)需要處理POST表單的視圖函數(shù)加上@check_honeypot就行了,是不是很簡(jiǎn)單?
from common.decorators import check_honeypot
@check_honeypot
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return HttpResponseRedirect(reverse('users:profile'))
else:
form = SignUpForm()
return render(request, "users/signup.html", {"form": form, })
參考
本文核心代碼參考了James Sturk的Django-honeypot項(xiàng)目。原項(xiàng)目地址如下所示:
https://github.com/jamesturk/django-honeypot/
以上就是Django給表單添加honeypot驗(yàn)證增加安全性的詳細(xì)內(nèi)容,更多關(guān)于Django 添加honeypot驗(yàn)證的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- Django表單外鍵選項(xiàng)初始化的問(wèn)題及解決方法
- django表單中的按鈕獲取數(shù)據(jù)的實(shí)例分析
- Django def clean()函數(shù)對(duì)表單中的數(shù)據(jù)進(jìn)行驗(yàn)證操作
- Django 構(gòu)建模板form表單的兩種方法
- Django form表單與請(qǐng)求的生命周期步驟詳解
- Django model.py表單設(shè)置默認(rèn)值允許為空的操作
- Django表單提交后實(shí)現(xiàn)獲取相同name的不同value值
- Django框架獲取form表單數(shù)據(jù)方式總結(jié)
- django之從html頁(yè)面表單獲取輸入的數(shù)據(jù)實(shí)例
- 解決django中form表單設(shè)置action后無(wú)法回到原頁(yè)面的問(wèn)題
- django-xadmin根據(jù)當(dāng)前登錄用戶(hù)動(dòng)態(tài)設(shè)置表單字段默認(rèn)值方式