You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本连接Bitbucket Cloud遭401认证失败求助

Bitbucket Cloud API 401认证失败问题解决

核心问题分析

你的代码存在两处关键错误:

  • 重复认证方式冲突:同时使用了requests的auth参数和自定义Authorization请求头,两种认证逻辑叠加导致验证失败。
  • Authorization头格式错误:直接将app password填入Authorization头,不符合Bitbucket要求的Basic认证规范(需按Basic <base64编码的用户名:app_password>格式构造)。

正确的认证方式(二选一)

方式一:使用requests的auth参数(推荐)

Bitbucket Cloud API仅接受用户名+app password的组合认证,不能用普通账户密码。直接将这两个值传入auth参数,requests会自动处理Basic认证的编码逻辑:

def main(config):
    print("1")
    headers = {"Content-Type": 'application/json'}
    # 此处password必须是Bitbucket的app password,而非账户登录密码
    auth = (config["BITBUCKET"]["username"], config["BITBUCKET"]["app_password"])
    bb_base_url = f'https://api.bitbucket.org/2.0/repositories/'
    print("2")
    res = requests.get(bb_base_url, auth=auth, headers=headers)
    print("3")
    print(res.status_code)
    print(res.text)

方式二:手动构造Authorization头

若需自定义请求头,需将用户名:app_password字符串进行base64编码,再按规范拼接成Authorization头:

import base64

def main(config):
    print("1")
    # 构造Basic认证字符串
    auth_str = f"{config['BITBUCKET']['username']}:{config['BITBUCKET']['app_password']}"
    auth_bytes = auth_str.encode('utf-8')
    auth_base64 = base64.b64encode(auth_bytes).decode('utf-8')
    headers = {
        "Content-Type": 'application/json',
        "Authorization": f"Basic {auth_base64}"
    }
    bb_base_url = f'https://api.bitbucket.org/2.0/repositories/'
    print("2")
    res = requests.get(bb_base_url, headers=headers)
    print("3")
    print(res.status_code)
    print(res.text)

额外注意事项

  • 必须使用Bitbucket账户中创建的app password,不能用账户登录密码,且创建app password时需勾选对应权限(如仓库读写权限)。
  • 认证用的用户名是Bitbucket账户的用户名,而非注册邮箱。

内容的提问来源于stack exchange,提问作者Popchop3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:01:18