auth.json必须放在项目根目录或COMPOSER_HOME路径(如~/.composer/auth.json)才生效,按优先级顺序查找,路径错误则完全不读取;域名key须与仓库URL host完全一致,权限须为600,且不可提交至版本库。

auth.json 文件必须放在哪里才能生效
Composer 只会在特定位置查找 auth.json,顺序错了就完全不读取。它按以下优先级逐级向上查找:
- 当前项目根目录下的
auth.json -
COMPOSER_HOME环境变量指定路径(默认是~/.composer/或%APPDATA%\Composer\)下的auth.json - 全局配置目录(如 Linux/macOS 的
~/.config/composer/auth.json,但仅限 Composer 2.2+)
多数人误把文件丢进 vendor/ 或子目录,结果凭空调试半天——auth.json 必须在项目根或 Composer 全局配置路径下,且不能被 .gitignore 意外排除(私有仓库凭证常因此失效)。
白名单依赖的 repository 配置要和 auth.json 匹配
仅放对了 auth.json 不够,composer.json 里声明的私有源也得对得上。关键点是:host 必须与 auth.json 中的键名完全一致(包括端口、协议前缀)。
例如,若 auth.json 写的是:
{
"http-basic": {
"repo.example.com:8080": {
"username": "user",
"password": "token"
}
}
}
那 composer.json 的 repositories 就得这样写:
{
"repositories": [
{
"type": "composer",
"url": "https://repo.example.com:8080"
}
]
}
常见错误:
- URL 用
http://,但auth.json键名是https://repo.example.com(协议不一致 → 认证失败) - URL 带路径如
https://repo.example.com/api/v1,但auth.json键名只写了repo.example.com(路径不参与匹配,但 host 必须精确) - 用了自定义域名别名(如
myrepo.local),但 hosts 文件没配或 DNS 不通,导致连接超时而非认证失败
使用 bearer token 时 auth.json 格式容易写错
GitHub Packages、GitLab、Packagist.org 私有包等越来越多用 Bearer Token,但 auth.json 不支持直接写 "bearer": "xxx" —— 必须包装在 http-basic 下并伪造用户名,或改用 github-oauth(仅限 GitHub)。
正确写法(通用):
{
"http-basic": {
"gitlab.example.com": {
"username": "oauth2",
"password": "glpat-xxxxxxxxxxxxxxxxxxxx"
}
}
}
注意:username 字段在此场景下无实际意义,但不能为空;password 放 token 即可。若写成:
{ "bearer": { "gitlab.example.com": "glpat-..." } }
Composer 完全忽略该字段,报错是 401 Unauthorized,但不会提示配置格式错误。
敏感信息泄露风险比想象中高
auth.json 一旦提交到 Git,私有源凭证就彻底暴露。即使加了 .gitignore,也要检查是否已缓存:
- 运行
git check-ignore -v auth.json确认忽略生效 - 如果文件已被追踪,需先执行
git rm --cached auth.json,再提交 - CI 环境中不要硬编码凭证,应通过环境变量注入(Composer 2.2+ 支持
COMPOSER_AUTH环境变量传入 base64 编码的完整auth.json内容)
最易被忽略的一点:某些 IDE(如 PHPStorm)会自动在项目根生成 auth.json 并标记为“已添加”,开发者没注意就直接 commit 了。


















