需在 composer.json 的 repositories 字段添加 type 为 vcs 的配置,指向 GitLab 项目 HTTPS 或 SSH 地址,并通过 auth.json 配置 Personal Access Token(username 为 oauth2,password 为 glpat-xxx),同时确保私有包 composer.json 中的 name 与引用名一致。

怎么在 composer.json 里声明 GitLab 私有仓库
Composer 默认只认 Packagist,要拉取 GitLab 上的私有包,必须显式告诉它“这个仓库在哪、怎么认证、用什么协议”。核心是往 composer.json 的 repositories 字段里加一条类型为 vcs 的配置,指向你的 GitLab 项目 HTTPS 或 SSH 地址。
常见错误是直接写 https://gitlab.example.com/group/pkg.git 却没配认证,结果 composer install 卡在 “Could not fetch https://gitlab.example.com/group/pkg.git” 或报 401/403。HTTPS 方式必须配 auth.json;SSH 方式则依赖本地 ~/.ssh/id_rsa 和 GitLab 账户已绑定公钥。
- HTTPS 示例(推荐用于 CI/CD):
"repositories": [ { "type": "vcs", "url": "https://gitlab.example.com/group/my-package.git" } ] - SSH 示例(适合开发者本地):
"url": "git@gitlab.example.com:group/my-package.git"
- 务必确认该 URL 能在命令行用
git clone成功拉下代码,否则 Composer 一定失败
auth.json 怎么配才能让 Composer 认 GitLab
GitLab 不支持 Composer 原生的 HTTP Basic Auth(即用户名密码直传),必须用 Personal Access Token(PAT)。这个 token 要有 read_api 和 read_repository 权限,不能用密码或 deploy token(后者不支持 API 调用)。
auth.json 必须放在用户主目录(~/.composer/auth.json)或项目根目录(./auth.json),且权限需设为 600,否则 Composer 会忽略它并报错 “Authentication required”。
- 正确内容示例:
{ "http-basic": { "gitlab.example.com": { "username": "oauth2", "password": "glpat-xxxxxxxxxxxxxxxxxxxx" } } } -
username固定填oauth2—— 这是 GitLab 的约定,不是你的账号名 -
password填你生成的 PAT,不是密码,也不是 token 名 - 如果 GitLab 启用了 2FA,PAT 是唯一可行方式;用密码会始终 401
为什么 composer require 拉不到私有包,却显示 “Package not found”
这不是网络或认证问题,而是 Composer 根本没去 GitLab 查——它只查 Packagist 和你 repositories 里明确列出的仓库。如果你的私有包没在 repositories 中声明,或者声明了但包名(vendor/name)和 GitLab 项目路径不一致,就会报这个错。
关键点:GitLab 仓库的 composer.json 里必须有正确的 name 字段,比如 "name": "mycompany/utils";而你在主项目中运行 composer require mycompany/utils,这个 mycompany/utils 必须和 GitLab 项目 URL 的路径(group/project)能对应上,否则 Composer 找不到源头。
- 检查私有包的
composer.json是否含"name",且格式为vendor/package - 确保
repositories的url指向的是该包的 Git 仓库地址,不是 GitLab 页面 URL - 运行
composer show -p看是否列出了你的私有包名;没列出说明repositories配置未生效或包名不匹配
CI/CD 中如何安全注入 GitLab Token
把 PAT 写死在 auth.json 里提交到 Git 是严重安全风险。CI 环境(如 GitLab CI)应通过环境变量注入,并在 job 开始时动态生成 auth.json。
GitLab CI 的 .gitlab-ci.yml 中,用 before_script 创建临时 auth.json,注意路径必须和 Composer 查找路径一致(通常为 $HOME/.composer/auth.json),且设置权限。
- 示例脚本:
before_script: - mkdir -p $HOME/.composer - echo '{"http-basic": {"gitlab.example.com": {"username": "oauth2", "password": "'$GITLAB_TOKEN'"}}}' > $HOME/.composer/auth.json - chmod 600 $HOME/.composer/auth.json -
$GITLAB_TOKEN是 GitLab CI 设置的 masked 变量,不能明文泄露 - 不要用
COMPOSER_AUTH环境变量——它只支持 Base64 编码的 JSON,容易出错且不直观 - 本地开发建议用
git config --global credential.helper store配合 HTTPS + PAT,避免每次输 token
私有仓库对接最常卡在认证链路断掉,而不是配置本身。重点盯住三处:GitLab PAT 权限是否开全、auth.json 路径和权限是否正确、私有包的 name 和 repositories.url 是否能逻辑对应。漏掉任一环,Composer 都只会安静地报一个模糊的“not found”。










