composer如何配置GitLab私有仓库_composer通过GitLab令牌安装包【教程】

11次阅读

composer 能从 gitLab 私有仓库安装包但需显式配置鉴权:必须在 composer.json 中声明 type 为 vcs 的仓库(URL 以 .git 结尾),gitlab 令牌需含 api scope,且 auth.json 中域名须与 GitLab 实例根域名一致、username 固定为 oauth2。

composer如何配置GitLab私有仓库_composer通过GitLab令牌安装包【教程】

Composer 能直接从 GitLab 私有仓库安装包,但默认不支持自动鉴权——必须显式配置 auth.json 或在 composer.json 中声明仓库类型与令牌,否则会卡在 Cloning into '...'... 或报 401 Unauthorized

GitLab 令牌必须用 api scope,不能只开 read_api

GitLab Personal access Token 需至少包含 api 权限(不是 read_repositoryread_api 单独项),因为 Composer 在获取包元数据(如 composer.json)时走的是 GitLab API 路径(/api/v4/projects/:id),而非 Git 协议。缺少 api 会导致 Could not fetch https://gitlab.example.com/api/v4/projects/... 错误。

  • 生成路径:https://gitlab.example.com/-/profile/personal_access_tokens
  • 勾选 api,其他权限按需添加(read_repository 可选,但非必需)
  • 令牌值仅显示一次,务必立即复制保存

composer.json 中必须声明 vcs 类型仓库

GitLab 私有项目不能靠 Composer 自动发现,必须手动在根 composer.jsonrepositories 字段中注册为 vcs 类型,并指向项目 HTTPS 克隆地址(不是 Web 页面 URL)。否则 Composer 会跳过该仓库,提示 Could not find package xxx at version yyy

{     "repositories": [         {             "type": "vcs",             "url": "https://gitlab.example.com/your-group/your-package.git"         }     ],     "require": {         "your-group/your-package": "^1.0"     } }
  • url 必须以 .git 结尾,且是可被 git clone 的 HTTPS 地址
  • 包名 your-group/your-package 需与目标仓库中 composer.json 内的 name 字段完全一致(区分大小写)
  • 不要用 package 类型手动定义——它绕过 GitLab API,无法利用令牌鉴权

auth.json 必须放在正确位置并启用凭证传递

Composer 默认不发送 HTTP 认证头,需通过 auth.json 显式注入 GitLab 令牌。该文件必须放在 Composer 配置目录下(全局生效),或与 composer.json 同级(项目级生效),且结构要严格匹配 GitLab 域名。

{     "http-basic": {         "gitlab.example.com": {             "username": "oauth2",             "password": "glpat-xxxxxxxxxxxxxxxxxxxx"         }     } }
  • username 固定填 oauth2(GitLab 要求),不是你的用户名
  • password 填完整令牌字符串(含 glpat- 前缀)
  • 文件路径示例:~/.composer/auth.jsonlinux/macOS)或 %appDATA%Composerauth.jsonwindows
  • 运行 composer config --global -e 可直接编辑全局配置,它会自动定位并打开 auth.json

最常被忽略的是:GitLab 实例启用了子路径(如 https://example.com/gitlab)时,auth.json 中的域名必须写成 example.com,而不是 example.com/gitlab;同时 repositories.url 仍要用完整 HTTPS 克隆地址(含子路径)。路径和域名不匹配,令牌就根本不会被附带发送。

text=ZqhQzanResources