如何配置 Composer 使用 OAuth Token 访问私有的 GitLab 或 Bitbucket 仓库?

1次阅读

composer 访问私有 git 仓库需配置 OAuth Tokenssh 密钥;gitlab 用 auth.json 存 token,Bitbucket 用 http-basic 结构配用户名和 app Password,并在 composer.json 的 repositories 中以 https URL 显式声明仓库。

如何配置 Composer 使用 OAuth Token 访问私有的 GitLab 或 Bitbucket 仓库?

Composer 默认无法直接访问私有 Git 仓库,需要配置 OAuth Token 或 SSH 密钥。对 GitLab 和 Bitbucket,推荐使用 OAuth Token 配合 Composer 的 auth.json 文件进行认证,既安全又便于 CI/CD 环境复用。

获取并配置 GitLab OAuth Token

登录 GitLab → Settings → access Tokens → 创建 Personal Access Token,勾选 read_repository(必要)和 api(可选,用于包元数据探测)。复制生成的 token。

在项目根目录或全局 Composer 配置目录(如 ~/.composer/auth.json)中,编辑或创建 auth.json

{     "gitlab.com": {         "token": "glpat-xxxxxxxxxxxxxxxxxxxx"     } }

确保该文件权限为 600linux/macOS):
chmod 600 auth.json

获取并配置 Bitbucket OAuth Token

Bitbucket 不支持传统 OAuth 1.0a Token,需使用 App Password(本质是 OAuth2 风格凭证):
→ 进入 Bitbucket 设置 → App passwords → 创建新密码,权限至少勾选 Repositories: Read

auth.json 中添加:

{     "bitbucket.org": {         "http-basic": {             "bitbucket.org": {                 "username": "your-bitbucket-username",                 "password": "app-password-generated-above"             }         }     } }

注意:Bitbucket 不接受纯 token 字段,必须用 http-basic 结构,并提供用户名 + App Password 组合。

如何配置 Composer 使用 OAuth Token 访问私有的 GitLab 或 Bitbucket 仓库?

Explainpaper

阅读学术论文的更好方法,你的学术论文阅读助手。

如何配置 Composer 使用 OAuth Token 访问私有的 GitLab 或 Bitbucket 仓库? 89

查看详情 如何配置 Composer 使用 OAuth Token 访问私有的 GitLab 或 Bitbucket 仓库?

composer.json 中正确声明私有仓库

不能只靠 auth.json 自动识别;必须在 composer.jsonrepositories 中显式声明仓库类型与 URL:

  • GitLab 示例(HTTPS):
    "type": "vcs", "url": "https://gitlab.com/your-group/your-private-package.git"
  • Bitbucket 示例(HTTPS):
    "type": "vcs", "url": "https://bitbucket.org/your-workspace/your-private-package.git"

确保 URL 是 HTTPS 格式(不是 git@…),否则 Composer 不会触发 HTTP 认证流程,auth.json 将被忽略。

验证与调试技巧

运行 composer install -vvv 查看详细日志,确认是否调用了认证头(如 Authorization: Bearer …Authorization: Basic …)。

若仍失败,检查:
auth.json 是否在有效路径(项目级优先于全局)
– Token 是否过期或权限不足
– GitLab/Bitbucket 账户是否对目标仓库有读取权限
– 是否启用了两步验证(Bitbucket App Password 必须在 2FA 开启后创建)

基本上就这些。不复杂但容易忽略 URL 协议和 auth.json 结构细节。

text=ZqhQzanResources