【CMDB】API传输验证
客户端向服务器发送请求时,在请求头添加自定义的字符串
客户端的加密方式
1.对key+time进行md5加密
2.发送的时候的格式为md5_key|time,将时间也发送过去
服务器端验证
1.获取加密的字符串,md5_key | time
2.判断时间time是否超时
3.验证md5_key
4.判断md5_key 在短时间内是否访问过,用redis,访问过则不通过
client
import time
import hashlib
import requests
# 每台client都有一个key,跟server对应
ENCRYPTION_KEY= 'abcdedf'
now_time = time.time()
# key的格式定义
key = "%s|%s" %(ENCRYPTION_KEY ,now_time)
# md5加密
md5 = hashlib.md5()
md5.update(key.encode('utf-8'))
new_key = md5.hexdigest()
# 发送加密字符串的格式
send_key = "%s|%s" %(new_key ,now_time)
headers = {"clientkey" :send_key}
print(headers)
r = requests.get("http://127.0.0.1:8000/api/asset.html",headers=headers)
print(r.text)
server
import time
from functools import wraps
from django.conf import settings
import hashlib
key_dict = {}
# Create your views here.
def check_key(func):
@wraps(func)
def inner(request):
accept_key = request.META.get("HTTP_CLIENTKEY", None)
if not accept_key:
return HttpResponse("非法链接")
else:
now_time = time.time()
old_md5_key, old_time = accept_key.split('|')
float_old_time = float(old_time)
# 判断时间是否超时
if now_time - float_old_time > 10:
return HttpResponse("超时")
else:
# 判断md5是否正确
key = "%s|%s" % (settings.AC_KEY, old_time)
md5 = hashlib.md5()
md5.update(key.encode('utf-8'))
new_md5_key = md5.hexdigest()
if new_md5_key != old_md5_key:
return HttpResponse("加密的key有误")
# 循环字典,删除超过10秒的key
for t in list(key_dict.keys()):
if now_time - key_dict[t] > 10:
del key_dict[t]
# 判断10秒内是否访问过
if old_md5_key in key_dict:
return HttpResponse("已经访问过")
key_dict[old_md5_key] = now_time
r = func(request)
return r
return inner