代理模式调用FreshDesk API返回invalid_credentials错误如何解决?
错误根因
你在代理请求的代码中,将FreshDesk平台的API身份凭证赋值给了Proxy-Authorization请求头,这个头是用于代理服务器身份校验的,凭证只会发送给代理,不会传递到目标FreshDesk服务端,导致FreshDesk没有收到有效身份信息,返回鉴权失败。
推荐解决方案:使用requests原生代理能力(无需手动处理隧道逻辑)
requests本身支持配置代理,可直接复用你原来无代理时的鉴权逻辑,仅需额外添加代理配置即可,代码如下:
import requests import os from requests.auth import HTTPBasicAuth method = "get" url = "https://mycompanydomain.freshdesk.com/api/v2/tickets" apiKey = "XXXXXXXXX" secret = "x" os.environ["REQUESTS_CA_BUNDLE"] = "Path to CA Certs" auth = HTTPBasicAuth(apiKey, secret) # 新增代理配置 proxies = { "http": "http://11.125.250.121:3128", "https": "http://11.125.250.121:3128" } # 如果代理本身需要身份认证,把代理账号密码填到代理地址里即可,示例:"https": "http://代理用户名:代理密码@11.125.250.121:3128" rsp = requests.request(method, url, headers=None, auth=auth, proxies=proxies) print(rsp.text)
若需保留http.client的实现方式,修正代码如下
需要同时配置代理授权头和FreshDesk服务的授权头,如果你的代理不需要鉴权,甚至不需要配置Proxy-Authorization:
import base64 import http.client method = "get" apiKey = "XXXXXXXX" secret = "x" # 1. 生成FreshDesk服务的身份认证凭证 fd_cred= '{}:{}'.format(apiKey, secret) fd_cred = base64.b64encode(fd_cred.encode('utf-8')).decode('utf-8') # 如果你的代理本身需要鉴权,再单独生成代理的凭证填到Proxy-Authorization,这里示例代理不需要鉴权,所以不填 # proxy_cred = '代理用户名:代理密码' # proxy_cred = base64.b64encode(proxy_cred.encode('utf-8')).decode('utf-8') # proxy_headers = {'Proxy-Authorization': f'Basic {proxy_cred}'} conn = http.client.HTTPSConnection("11.125.250.121", 3128) conn.set_tunnel("mycompanydomain.freshdesk.com") # 代理不需要鉴权就不用传headers,需要就传上面的proxy_headers # 2. 把FreshDesk的认证凭证加到发送给目标服务的请求头里 headers = { 'Content-Type' : 'application/json', 'Authorization': f'Basic {fd_cred}' } conn.request("GET", "/api/v2/tickets",headers = headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
内容的提问来源于stack exchange,提问作者peerpressure
相关产品推荐
相关产品推荐

