通常公司對外的接口都會用到sign簽名,對不一樣的客戶提供不一樣的apikey ,這樣能夠提升接口請求的安全性,避免被人抓包後亂請求。
sign簽名是一種很常見的方式
關於sign簽名的能夠參考前面一篇的介紹http://www.javashuo.com/article/p-ylxuckrs-dq.htmlhtml
一登錄的接口請求爲例,以下接口抓包報文信息,其中sign的簽名規則以下python
POST http://127.0.0.1:8000/api/v3/login HTTP/1.1 User-Agent: Fiddler Content-Type: application/json Host: 127.0.0.1:8000 Content-Length: 111 { "username": "test", "password": "123456", "sign": "1aca01806e93bb408041965a817666af" } HTTP/1.1 200 OK Date: Sat, 26 Oct 2019 03:38:31 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: application/json Vary: Accept, Cookie Allow: POST, OPTIONS X-Frame-Options: SAMEORIGIN Content-Length: 109 {"code": 0, "msg": "login success!", "username": "test", "token": "a76ba3b8fcbdff82f6a94e5ad5bf8fb934192e5f"}
使用httprunner框架寫腳本json
- config: name: logincase variables: {} - test: name: login case1 request: url: http://127.0.0.1:8000/api/v3/login method: POST headers: Content-Type: application/json User-Agent: python-requests/2.18.4 json: username: test password: "123456" setup_hooks: - ${setup_request($request)} validate: - eq: [status_code, 200] - eq: [headers.Content-Type, application/json] - eq: [content.msg, login success!] - eq: [content.code, 0]
在debugtalk.py 編寫setup_hook函數,對請求的body部分預處理api
import hashlib def sign_body(body, apikey="12345678"): '''請求body sign簽名''' # 列表生成式,生成key=value格式 a = ["".join(i) for i in body.items() if i[1] and i[0] != "sign"] # print(a) # 參數名ASCII碼從小到大排序 strA = "".join(sorted(a)) # print(strA) # 在strA後面拼接上apiKey獲得striSignTemp字符串 striSignTemp = strA+apikey # 將strSignTemp字符串轉換爲小寫字符串後進行MD5運算 # MD5加密 def jiamimd5(src): m = hashlib.md5() m.update(src.encode('UTF-8')) return m.hexdigest() sign = jiamimd5(striSignTemp.lower()) # print(sign) return sign def setup_request(request): '''setuphook函數,發請求前預處理''' body = request.get("json") print(body) # 由body請求參數生成sign值 sign = sign_body(body, apikey="12345678") print("sign值:%s" % sign) request["json"]["sign"] = sign if __name__ == '__main__': body = { "username": "test", "password": "123456" } print(sign_body(body))
運行用例安全
D:\soft\HELL\DEMO>hrun login_sign_demo.yml login case1 {'username': 'test', 'password': '123456'} sign值:1aca01806e93bb408041965a817666af INFO POST http://127.0.0.1:8000/api/v3/login INFO status_code: 200, response_time(ms): 689.84 ms, response_length: 109 bytes INFO start to validate. . ---------------------------------------------------------------------- Ran 1 test in 0.698s OK INFO Start to render Html report ... INFO Generated Html report: D:\soft\HELL\DEMO\reports\1572062969.html D:\soft\HELL\DEMO>