API验证

def asset(request):
    client_md5_time_key=request.META.get('HTTP_OPENKEY')
    client_md5_key,client_ctime=client_md5_time_key.split('|')
    client_ctime=float(client_ctime)
    server_time=time.time()
    #时间验证,用服务器时间减去客户端提交时间,如果大于一定范围,即认定链接有问题,返回错误消息
    if server_time-client_ctime>10:
        return HttpResponse("连接超时,请检查后重新连接")
    #规则验证,使用自己定义的字符串与时间生成MD5值,如果值提交错误,返回错误消息
    temp="%s|%s"%(settings.AUTH_KEY,client_ctime)
    m=hashlib.md5()
    m.update(bytes(temp,encoding="utf-8"))
    server_md5_key=m.hexdigest()
    if server_md5_key !=client_md5_key:
        return HttpResponse("认证失败")

    #使用列表维护验证信息,清除超时信息,拒绝重复验证信息连接
    for k in list(api_key_record.keys()):#此处循环的是字典的键,因为在循环字典本身时无法删除正在迭代的数据
        v=api_key_record[k]#因为需要使用字典键值循环判断
        if server_time>v:
            del api_key_record[k]
    if client_md5_time_key in api_key_record:
        return HttpResponse("拒绝重复链接")
    else:
        api_key_record[client_md5_time_key]=client_ctime+10
    if request.method=="GET":
        return HttpResponse("私密数据,不展示")

API验证还有一种是基于数据层的加密,使用RAS对数据进行加密,即使API层面没有保护,也不会影响数据的安全,而且数据由于加密,没有实际意义,也不会造成损失

posted @ 2017-07-31 17:05  左岸边  阅读(163)  评论(0编辑  收藏  举报