Python带Basic认证与Token的POST请求返回403问题排查
问题分析与修正方案
你的POST请求存在几个可能导致403的问题,对应修正如下:
1. 缺少Content-Type请求头
你用json.dumps(test_data)把列表转成了JSON字符串,但没告诉服务器请求体是JSON格式。Postman发送JSON请求时会自动添加Content-Type: application/json头,而Python代码里没加,服务器可能无法正确解析请求体,返回403。
修正方法二选一:
- 直接用
json参数替代data,requests会自动设置Content-Type头:
requests.post(POST_url, json=test_data, headers={"x-csrf-token":token}, auth=auth)
- 手动添加请求头:
headers = { "x-csrf-token": token, "Content-Type": "application/json" } requests.post(POST_url, data=json.dumps(test_data), headers=headers, auth=auth)
2. 未保持会话Cookie
很多CSRF机制要求Token和请求的Cookie绑定,GET请求获取Token时,服务器会在响应中设置Cookie,Postman会自动保存并在后续请求中携带,但你的代码是分开的get和post请求,默认不会共享Cookie,导致Token与Cookie不匹配,触发403。
修正方法:使用requests.Session()维持会话,自动管理Cookie:
session = requests.Session() session.auth = HTTPBasicAuth('User', 'Password') # 获取Token,会话自动保存Cookie response = session.get(URL_token, headers={"x-csrf-token":"FETCH"}) token = response.headers['x-csrf-token'] # 发送POST请求,会话自动携带之前的Cookie response = session.post(POST_url, json=test_data, headers={"x-csrf-token":token})
额外检查点
- 确认
test_data的结构、字段名大小写和Postman中发送的完全一致; - 打印
token值,和Postman中拿到的对比,确保GET请求确实获取到了有效Token。
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

