接口的鉴权&响应数据解密

前言:

1、开放的接口为了避免被别人攻击,频繁刷接口,浪费服务器资源,这就涉及到签名(Signature)加密了

2、API 使用签名方法(Signature)对接口进行鉴权(Authentication)。每一次请求都需要在请求中包含签名信息, 以验证用户身份。

一、我们的接口请求:

1、登录的url + key(一段已知的字符串) + get请求带上固定参数(有一个变动的时间戳)拼接成新的请求链接

2、拼接之后的链接通过 hashlib.md5 加密

3、加密之后的数据就是鉴权ydtoken

5、再把这个ydtoken传到每个接口请求的参数里面去,请求才能成功    

二、鉴权的代码操作

# -*- coding:utf-8 -*-
from common import commons
import readConfig as readConfig
import hashlib


localReadConfig = readConfig.ReadConfig()


class getAuthentication(object):

    def  get_Url(self,xlse_name,name,row=0,col=1):
        '''
        从excel里面获取登录的url,账号和密码,然后 url+固定参数,拼接成新的请求链接URL
        '''
        api_v = localReadConfig.get_http('api')
        local_xls = commons.get_xls(xlse_name,name)
        url = local_xls[row][col]
        par = self.add_par()
        get_url = '/'+api_v+url + "?" + par
        return get_url


    def add_par(self):
        # 固定参数:时间戳+固定参数,拼接成 a=1&b+2&c=3 的模式
        fixed_parameter= localReadConfig.get_parameters()
        list_a=[]
        for key in dict(fixed_parameter):
            list_a.append( key+'='+fixed_parameter[key])
            list_b = '&'.join(list_a)
        return list_b

    def get_ydtoken(self,url):
        # 拼接之后的链接URL + 固定字符串 就行md5 加密,生成鉴权数据
        # print((md5str))
        key = "固定字符串"
        new_md5str = key + url
        # print(new_md5str)
        byte_md5str = bytes(new_md5str, encoding="utf8")   #必须传byte
        ydtoken =hashlib.md5(byte_md5str).hexdigest()
        return ydtoken

运行后的结果:

三、fiddler抓看响应时间,是加密后的数据,需要使用base64解密

代码操作

  def get(self):
        try:
            r = requests.get(self.url, headers=self.headers, params=self.params, timeout=float(timeout))
            print(r.url)
            result = decodeToBase64(r.content) #decodeToBase64封装了解密方法,每个公司都会做一些改动,就不贴出来了
            response = json.loads(result)
            # response.raise_for_status()
            return response
        except TimeoutError:
            self.logger.error("Time out!")
            return None

解码之后:

原文地址:https://www.cnblogs.com/guo2733/p/10543045.html