auth.json 应优先放在项目根目录,其次为全局配置目录(如 ~/.composer/auth.json),最高优先级是 COMPOSER_AUTH 环境变量;生产环境推荐项目级配置,CI/CD 场景建议用环境变量注入。

auth.json 文件应该放在哪里?
Composer 会按顺序查找 auth.json,优先级从高到低是:COMPOSER_AUTH 环境变量 → 当前项目根目录下的 auth.json → 全局配置目录(COMPOSER_HOME,通常是 ~/.composer/auth.json 或 %APPDATA%\Composer\auth.json)。生产环境推荐用项目级配置,避免凭据泄露;CI/CD 场景建议用环境变量注入。
auth.json 的基本结构和 token 类型选择
私有 Git 仓库(如 GitHub、GitLab、Bitbucket)通常支持两种凭据:个人访问令牌(PAT)或 OAuth token。不推荐用账号密码——GitHub 已禁用密码认证,GitLab 也默认关闭。PAT 必须至少有 read_package_registry(GitLab)或 read:packages(GitHub)权限。
常见错误现象:401 Unauthorized 或 Could not fetch https://gitlab.example.com/api/v4/projects/…,往往是因为 token 权限不足或过期。
{
"http-basic": {
"packagist.example.com": {
"username": "your-username",
"password": "your-api-token"
}
},
"github-oauth": {
"github.com": "ghp_abc123def456..."
},
"gitlab-token": {
"gitlab.example.com": "glpat-xyz789..."
}
}
-
http-basic适用于私有 Packagist 镜像或支持 Basic Auth 的私有仓库 -
github-oauth仅对 github.com 生效,值必须是 GitHub PAT(不是 OAuth App token) -
gitlab-token是 GitLab 15.2+ 引入的专用字段,比http-basic更安全(不拼接用户名)
如何让 Composer 在安装时自动读取凭据?
只要 auth.json 位置正确且 JSON 格式合法,Composer 会在每次执行 composer install 或 composer update 时自动加载。不需要额外命令或配置项启用。
容易踩的坑:
- 文件权限问题:Linux/macOS 下,
auth.json不应设为全局可读(chmod 600 auth.json),否则 Composer 会拒绝加载并报错auth.json is not secure, ignoring - JSON 语法错误:多一个逗号、少一个引号都会导致整个凭据失效,错误提示常为
Invalid credentials configuration - 未启用仓库源:仅配了
auth.json不够,还需在composer.json的repositories中声明对应私有仓库,例如:"repositories": [ { "type": "composer", "url": "https://packagist.example.com" } ]
CI/CD 中安全注入凭据的最佳实践
把 token 写死在 auth.json 提交到代码库是严重风险。正确做法是运行时生成临时 auth.json,用环境变量注入后再执行 Composer 命令。
GitHub Actions 示例(使用 jq 构建):
echo '{"http-basic":{"packagist.example.com":{"username":"$USERNAME","password":"$TOKEN"}}}' | jq -r --arg u "$USERNAME" --arg t "$TOKEN" '{ "http-basic": { "packagist.example.com": { "username": $u, "password": $t } } }' > auth.json
GitLab CI 可直接用 before_script 生成:
echo "{\"gitlab-token\":{\"gitlab.example.com\":\"$GITLAB_TOKEN\"}}" > auth.json
关键点:确保 auth.json 在作业结束前被清理(或限定作用域),且 CI 变量标记为“masked”和“protected”。
复杂点在于不同平台对 token 类型和字段名的要求不一致,比如 Bitbucket Server 要用 http-basic + 用户名+App Password,而 GitHub Packages 则依赖 github-oauth 或 auth.json 中的 token 字段配合 composer.json 的 repository type 设置。漏掉任一环节,就会卡在 403 或 404。









