在django中实现全站api签名验证,核心做法是编写一个自定义中间件类,在请求到达视图前拦截并校验签名。你需要从请求头或查询参数中提取时间戳、随机数和签名值,结合共享密钥和请求体计算hmac-sha256哈希,并与客户端提供的签名比对,同时检查时间戳防重放。配置好该中间件后,所有未通过签名的请求将被拒绝。

如何提取请求中的签名要素并进行基础校验
首先需要从HTTP请求中获取用于验签的关键字段,通常包括timestamp(时间戳)、nonce(随机数)和sign(签名值)。这些字段可以放在Authorization头部或作为URL参数传递。中间件需要解析这些值,并初步判断其是否存在且格式正确。

import hashlib
import hmac
import time
from django.utils.deprecation import MiddlewareMixin
class APISignatureMiddleware(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
# 实际项目中应从配置读取
self.secret_key = b'my_secret_key'
self.allowed_drift = 300 # 允许5分钟的时间偏差
def process_request(self, request):
# 1. 获取签名要素
timestamp = request.GET.get('timestamp') or request.META.get('HTTP_TIMESTAMP')
nonce = request.GET.get('nonce') or request.META.get('HTTP_NONCE')
sign = request.GET.get('sign') or request.META.get('HTTP_SIGN')
if not all([timestamp, nonce, sign]):
return HttpResponseBadRequest("Missing signature parameters")
# 2. 校验时间戳防重放
try:
req_time = int(timestamp)
except ValueError:
return HttpResponseBadRequest("Invalid timestamp")
current_time = int(time.time())
if abs(current_time - req_time) > self.allowed_drift:
return HttpResponseForbidden("Timestamp expired")
# 3. 构建待签名字符串 (简化版: method + path + timestamp + nonce)
raw_string = f"{request.method}{request.path}{timestamp}{nonce}"
# 4. 计算期望签名
expected_sign = hmac.new(
self.secret_key,
raw_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
# 5. 比对签名
if not hmac.compare_digest(expected_sign, sign):
return HttpResponseForbidden("Invalid signature")
return None
如何处理请求体变化导致的签名不一致问题
当API涉及POST或PUT请求时,请求体(Body)的变化会直接影响签名结果。如果客户端在发送请求后修改了Body,或者服务端在处理过程中改变了Body内容,签名将失效。因此,必须在中间件中读取原始请求体进行验签,并确保后续视图能访问到相同的Body数据。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

# 在process_request中读取body
raw_body = request.body
# 注意:request.body只能读取一次,需缓存
request._cached_body = raw_body
# 构建包含body的签名字符串
raw_string_with_body = f"{request.method}{request.path}{timestamp}{nonce}{raw_body.decode('utf-8')}"
expected_sign = hmac.new(
self.secret_key,
raw_string_with_body.encode('utf-8'),
hashlib.sha256
).hexdigest()
基于特定输入条件如空Body时的签名行为是什么
当请求没有Body(如GET请求)时,request.body为空字节串'b''。此时构建签名字符串应不包含Body部分,或显式使用空字符串。若代码错误地尝试解码空Body为UTF-8字符串并拼接,可能导致签名不一致。正确的做法是判断request.body是否为空,若为空则忽略Body参与签名计算,确保与客户端逻辑一致。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










