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

Composer 能直接从 GitLab 私有仓库安装包,但默认不支持自动鉴权——必须显式配置 auth.json 或在 composer.json 中声明仓库类型与令牌,否则会卡在 Cloning into '...'... 或报 401 Unauthorized。
GitLab 令牌必须用 api scope,不能只开 read_api
GitLab Personal Access Token 需至少包含 api 权限(不是 read_repository 或 read_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.json 的 repositories 字段中注册为 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.json(Linux/macOS)或%APPDATA%\Composer\auth.json(Windows) - 运行
composer config --global -e可直接编辑全局配置,它会自动定位并打开auth.json
最常被忽略的是:GitLab 实例启用了子路径(如 https://example.com/gitlab)时,auth.json 中的域名必须写成 example.com,而不是 example.com/gitlab;同时 repositories.url 仍要用完整 HTTPS 克隆地址(含子路径)。路径和域名不匹配,令牌就根本不会被附带发送。










