Composer怎么配置GitLab Token 私有GitLab认证设置【教程】

10次阅读

composer 识别 gitLab Personal access Token 需在 auth.json 中以 http-basic 方式显式配置,域名必须严格匹配 https 仓库 URL(含协议和端口),用户名任意、密码为 token,且 ssh URL 会绕过该认证机制。

Composer怎么配置GitLab Token 私有GitLab认证设置【教程】

Composer 无法拉取私有 gitlab 仓库,根本原因通常是未配置有效的 GitLab Personal Access Token 或认证方式不匹配。直接在 auth.json 中写 token 是最稳定、最可控的方式,其他方法(如环境变量、Git 凭据管理器)容易被忽略或覆盖。

怎么让 Composer 识别 GitLab 的 Personal Access Token

Composer 不会自动读取 GitLab 的 token,必须显式声明为 HTTP Basic 认证凭据。GitLab 的 token 在 Composer 中等价于密码,用户名可任意(如 gitlab-token),但必须配对使用。

  • 生成 token 时勾选 read_apiread_repository(若用 SSH 克隆则不需要,但 Composer 默认走 HTTPS)
  • token 必须存放在用户级 auth.json~/.composer/auth.json)或项目级 auth.json(与 composer.json 同目录)
  • 格式严格:域名必须带协议和端口(如 https://gitlab.example.com),不能省略 https://
{     "http-basic": {         "https://gitlab.example.com": {             "username": "gitlab-token",             "password": "glpat-xxxxxxxxxxxxxxxxxxxx"         }     } }

为什么gitlab.example.com 而不是 git@gitlab.example.com

Composer 解析仓库 URL 时,只对 HTTPS 协议触发 http-basic 认证;SSH 地址(如 git@gitlab.example.com:group/repo.git)完全绕过此机制,走系统 SSH 配置。一旦 composer.json 中的 repository type 是 vcs 且 URL 是 HTTPS,就必须用 http-basic

  • 检查你的 composer.jsonrepositories 的 URL 是否以 https:// 开头
  • 如果用了 git+ssh://git@gitlab...,Composer 不会查 auth.json,而是依赖 ssh-agent~/.ssh/config
  • 混用 HTTPS URL 和 SSH 凭据会导致静默失败(如 Could not fetch401 Unauthorized

composer config --global 设置是否生效

执行 composer config --global http-basic.gitlab.example.com gitlab-token glpat-xxx 确实会写入 ~/.composer/auth.json,但要注意两点:

  • 该命令生成的域名键名默认不带 https://,而 Composer 7.2+ 要求严格匹配(即必须是 "https://gitlab.example.com",不能是 "gitlab.example.com"
  • 如果项目目录下存在 auth.json,它会优先于全局配置,容易造成调试时误判
  • 运行 composer config --global --list | grep http-basic 可确认实际写入的 key 名

最容易被忽略的是:GitLab 自托管实例的域名必须和仓库 URL 完全一致(包括子路径,如 https://gitlab.example.com/group/subgroup 不等于 https://gitlab.example.com),少一个斜杠或协议都导致认证失效。

text=ZqhQzanResources