使用MITMProxy转发请求到本地、保存鉴权给本地请求
背景:
1.公司项目,没有前端项目,无法起前端,无法验证本地接口
2.接口鉴权OATH2,使用postman调试每次都要取浏览器复制Authorization头,还会频繁过期,影响效率
方案:使用MITMProxy自定义流量处理
MITMProxy是一种用于中间人攻击(Man-in-the-middle attack)的代理工具。它的作用是在正常的代理功能基础上,截获、记录或篡改数据,并自定义特定的行为。与其他抓包工具(如Fiddler或Wireshark)不同的是,MITMProxy不仅可以查看和分析截获的请求,还可以通过自定义脚本进行二次开发。例如,可以截获浏览器对特定URL的请求,将返回内容置空并存储真实的返回内容到数据库,并在出现异常时发送邮件通知。与Fiddler类似的需求无法实现高度定制化,而MITMProxy可通过载入自定义Python脚本轻松实现。
安装:brew install mitmproxy
脚本:
# mitmproxy script to intercept and modify requests from mitmproxy import http import os TOKEN_FILE_PATH = "/Users/xy/workspace/python/mitmproxy/token_file.txt" LOG_FILE_PATH = "/Users/xy/workspace/python/mitmproxy/log_file.txt" def save_log_to_file(log): with open(LOG_FILE_PATH, "a") as file: file.writelines(log+"\n") def save_token_to_file(token): with open(TOKEN_FILE_PATH, "w") as file: file.write(token) def load_token_from_file(): if os.path.exists(TOKEN_FILE_PATH): with open(TOKEN_FILE_PATH, "r") as file: token = file.read().strip() return token return None def request(flow: http.HTTPFlow) -> None: #保存dev的鉴权 # Check if the host is a.com and save the token if "dev-oa.xx.com" in flow.request.pretty_host: save_log_to_file('---->dev-oa.xx.com') token = flow.request.headers.get("Authorization") if token: save_log_to_file('save token') save_log_to_file(token) save_token_to_file(token) # Modify the request URL to dev_a.com # flow.request.host = "dev_a.com" # Check if the host is b.com and inject the token #使用保存的鉴权覆盖本地的请求 elif "127.0.0.1" in flow.request.pretty_host: save_log_to_file('---->127.0.0.1') token = load_token_from_file() if token: save_log_to_file('token') save_log_to_file(token) flow.request.headers["Authorization"] = token #将dev的前端请求转发给本地 # Replace dev-oa.xx.com/flow with 127.0.0.1:9099 if "dev-oa.xx.com/flow/h5" in flow.request.pretty_url or "dev-oa.xx.com/flow/admin" in flow.request.pretty_url: # if False: flow.request.host = "127.0.0.1" flow.request.port = 9099 flow.request.scheme = "http" flow.request.path = flow.request.path.replace("/flow", "",1)
启动:mitmproxy -s modify_request.py -p 8089
注意那两个文件的权限
然后在系统设置代理 127.0.0.1 8089