需在 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": "[email protected]: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 项目路径不一致,就会报这个错。