Django学习手册

原理分析:

  API接口验证

  1.一个认证的key server端 和 client端都必须有这么一个认证key。

  2.认证登录的时间限定

  3.保存已验证的信息,在以后的验证不能再次登录

client 端:

import requests
import hashlib
import time

# 基于验证的key
au_key = "dawefgdsfsafdsadas"

# 基于验证的时间
au_time = time.time()

# 将验证的key与时间合并成一个字符
au_key_time = "%s|%s"%(au_key,au_time)

# 将合并的字符进行MD5加密
m = hashlib.md5()
m.update(bytes(au_key_time,encoding='utf-8'))
authkey = m.hexdigest()

# 将生成加密的 KEY 与 时间传递至服务端
url = "http://127.0.0.1:8000/index/"
data = {"a":1,'b':"2",'c':3,'d':4}
headers = {'authkey':authkey,'autime':str(au_time)}

a = requests.post(url=url,data=data,headers=headers)
print(a.text)

server 端views:

from django.shortcuts import render,HttpResponse
import hashlib
import time
# Create your views here.

au_list = []

def index(request):

    # 与client端一致的验证key
    au_key = "dawefgdsfsafdsadas"
    # 从请求头中取出client端 加密前的时间
    client_au_time = request.META['HTTP_AUTIME']

    # 将服务端的key 与 client的时间合并成字符
    server_au_key = "%s|%s" % (au_key, client_au_time)

    # 然后将字符也同样进行MD5加密
    m = hashlib.md5()
    m.update(bytes(server_au_key, encoding='utf-8'))
    authkey = m.hexdigest()

    # 取出client端加密的key
    clint_au_key = request.META['HTTP_AUTHKEY']


    # 三重验证机制

    # 1.超出访问时间5s后不予验证通过。
    server_time = time.time()
    if server_time - 5 > float(client_au_time):
        return HttpResponse("超时!")

    # 2.服务端加密的key值 跟 client发过来的加密key比对是否一致?
    if authkey != clint_au_key:
        return HttpResponse("验证失败!")

    # 3.比对当前的key值是否是以前访问过的,访问过的也不予验证通过。
    if authkey in au_list:
        return HttpResponse("验证码已过期")

    # 将成功登陆的key值保存在列表中。
    au_list.append(authkey)

    return HttpResponse("OK")
原文地址:https://www.cnblogs.com/Anec/p/10058430.html