认证三关
认证:
三关:(从源码中来的)
- 时间超时
- 访问记录
- MD5值比较
Django中只有最后一关,验证的KEY在settings.py文件中
和tornado中一模一样
客户端
import requests import time import hashlib AUTH_KET = "dfbsadakGHKSGDKAScajhkafnz" def permit(url, data=None): # 获取当前的时间,跟AUTH_KEY一起MD5后发送 current_time = time.time() # 拼接字符串 key_with_time = "%s|%f" % (AUTH_KET, current_time) # md5加密 md5 = hashlib.md5() md5.update(bytes(key_with_time, encoding="utf-8")) auth_key = md5.hexdigest() # 加密后的值 # 将加密后的字符串跟当前时间传过去 send_data = "%s|%f" % (auth_key, current_time) # 发送 return requests.post( url=url, json=data, headers={"authkey": send_data} ) resp = permit("http://127.0.0.1:8080/api/asset/") print(resp.text)
服务端
import time import hashlib # GLOBAL_VARIBLE AUTH_KEY = "dfbsadakGHKSGDKAScajhkafnz" # 验证秘钥 AUTH_TIME = 10 # 最长请求时间 KEY_LISTS = [] # 已经请求的秘钥列表 def auth_confirm(auth_data): """ 100: 登录成功 101: 请求超时 102: 用户已登录 103: 秘钥错误 :param auth_data: :return: """ # 获取key跟时间 auth_key, ctime = auth_data.split("|") auth_time = float(ctime) # 进行md5加密 auth_str = "%s|%f" % (AUTH_KEY, auth_time) md5 = hashlib.md5() md5.update(bytes(auth_str, encoding="utf-8")) final_key = md5.hexdigest() # 验证是否超时 if time.time() - AUTH_TIME > auth_time: # 超过认证时间 return 101 # 验证是否已经请求过 if auth_data in KEY_LISTS: # 已经请求过 return 102 # 验证秘钥是否正确 if not final_key == auth_key: # 秘钥不正确 return 103 # 通过验证,将本次秘钥存起来 KEY_LISTS.append(auth_data) return 100