使用Python Requests调用GitHub API出现Bad credentials错误
GitHub API请求401问题:参数传入Token失败但写死成功的解决方案
问题场景
通过Curl调用GitHub API生成组织自托管Runner注册令牌可正常返回结果,但使用Python requests库实现时,将token作为函数参数传入会返回<Response [401]> {'message': 'Bad credentials'}错误;若在函数内直接写死token则运行正常。
成功的Curl请求
curl -L \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer <MY-TOKEN>" \ -H "X-GitHub-Api-Version: 2022-11-28" \ https://api.github.com/orgs/<MY-ORG>/actions/runners/registration-token
失败的Python代码
def get_runner_token(token, org): url = f"https://api.github.com/orgs/{org}/actions/runners/registration-token" authorization = f'Bearer {token}' # 尝试过Bearer和直接token两种格式 headers = CaseInsensitiveDict() # 也尝试过普通dict headers['Accept'] = "application/vnd.github+json" # 尝试过移除Accept和API版本头 headers['Authorization'] = authorization headers['X-GitHub-Api-Version'] = "2022-11-28" payload = {} # 尝试过带/不带payload print("Sending request to", url, "with headers", headers) x = requests.post(url, headers=headers, data=payload) print(x, x.json())
成功的Python代码(写死token)
def get_runner_token(org): token = "..." # 直接写死的有效token # 其余逻辑和失败代码一致
核心原因分析
这类问题几乎都是传入的token参数存在隐性格式问题,常见情况:
- token包含首尾空格、换行符(比如从环境变量、配置文件读取时带入)
- 调用函数时传入了错误的变量(比如传成了用户名、其他密钥)
- token被意外截断或修改
排查与解决步骤
对比传入token与写死token的原始内容
在函数内打印repr(token),查看是否有多余的空白字符(如\n、),和写死的repr("...")对比。清理token格式
在拼接Authorization头前,先清理token的首尾空白:cleaned_token = token.strip() authorization = f'Bearer {cleaned_token}'验证请求头的一致性
打印生成的authorization字符串,和Curl中使用的Bearer <MY-TOKEN>完全对比,确保没有差异。检查函数调用参数
确认调用get_runner_token时,传入的第一个参数确实是有效的GitHub token,而非其他值。
修改后的示例代码
import requests def get_runner_token(token, org): # 清理token首尾空白,避免隐性格式问题 cleaned_token = token.strip() url = f"https://api.github.com/orgs/{org}/actions/runners/registration-token" headers = { 'Accept': "application/vnd.github+json", 'Authorization': f'Bearer {cleaned_token}', 'X-GitHub-Api-Version': "2022-11-28" } # 打印Authorization头用于排查 print("Authorization Header:", headers['Authorization']) response = requests.post(url, headers=headers) print(response, response.json())
内容的提问来源于stack exchange,提问作者Tomas Berger
相关产品推荐
相关产品推荐

