composer install 报“api rate limit exceeded”是因 github 对未认证 api 请求限流(每小时60次),需配置 oauth token 解决:执行 composer config --global github-oauth.github.com 将 token 写入 auth.json 并设权限为600,ci 中应通过安全环境变量注入,配后运行 composer clear-cache 并验证配置是否生效。

为什么 composer install 突然报 “API rate limit exceeded”
GitHub 对未认证的 API 请求有严格限制(每小时 60 次),Composer 在拉取私有包、或依赖中含 GitHub 仓库(如 "repo-url": "git@github.com:...")时,会走 GitHub API 查询 commit、tag、metadata —— 这部分不走 git 协议,而是走 HTTPS API,没令牌就直接撞限流。
典型错误信息:Could not fetch https://api.github.com/repos/xxx/yyy/commits/master, please create a GitHub OAuth token to go over the API rate limit
- 不是网络问题,也不是 Composer 版本低,是 GitHub 的 API 认证机制变了
- 即使你用 SSH 克隆代码,Composer 仍可能先调 API 获取元数据(尤其在
composer update或首次解析依赖时) - 公共包一般不受影响;但只要依赖链里有任何一个包的
source指向 GitHub(包括 packagist.org 上标记为 GitHub 的包),就可能触发
怎么配 GitHub OAuth Token 给 Composer 用
Token 不是配在 composer.json 里,而是写进 Composer 的全局配置(auth.json),让它自动在所有 GitHub API 请求头里带上 Authorization: Bearer xxx。
- 去 https://www.php.cn/link/9c450eb90c31bc12f1691f235da5a0cc 创建新 token,勾选
repo(读私有库必需)、read:packages(如果用 GitHub Packages)即可,不用给 admin 权限 - 执行命令写入配置:
composer config --global github-oauth.github.com <your-token-here></your-token-here> - 该命令会把 token 写进
~/.composer/auth.json(Linux/macOS)或%APPDATA%\Composer\auth.json(Windows),格式为:{"github-oauth": {"github.com": "xxx..."}} - 别手动编辑
auth.json—— 权限错误(比如 644 变成 600)或 JSON 格式错一个逗号,Composer 就静默忽略它
CI/CD 环境下怎么安全传入 Token
不能把 token 硬编码在 composer.json 或脚本里,也不能直接 echo $TOKEN | composer config ...(会留进 shell history)。CI 中要靠环境变量 + 临时配置。
- GitHub Actions:用
composer config github-oauth.github.com ${{ secrets.GITHUB_TOKEN }},注意secrets.GITHUB_TOKEN是 Actions 自带的,权限够用,无需额外创建 - GitLab CI / 自建 Jenkins:把 token 存为受保护变量(如
GH_COMPOSER_TOKEN),然后运行:composer config --global github-oauth.github.com "$GH_COMPOSER_TOKEN" - 容器构建中(Dockerfile):避免在构建层写入 token,改用
--build-arg+ 构建时临时注入,且确保镜像层不缓存含 token 的步骤 - 验证是否生效:运行
composer config --global --list | grep github-oauth,看到非空输出即表示已加载
Token 配了还是失败?检查这三件事
配完 token 还报限流,大概率是“看起来配了,其实没生效”,常见于路径、作用域或缓存干扰。
-
auth.json文件权限不对:Linux/macOS 下必须是600(chmod 600 ~/.composer/auth.json),否则 Composer 直接跳过读取 - 项目级配置覆盖了全局:检查项目根目录下是否有
auth.json,它会优先于全局配置;删掉或同步更新 - Composer 缓存了旧响应:执行
composer clear-cache,特别是之前失败过多次,API 返回的 403 响应可能被缓存了几分钟 - Token 已过期或被删:GitHub token 无法续期,只能重生成;如果用的是 GitHub App token 或 fine-grained token,请确认 scope 包含
contents: read
Token 本身不解决 git clone 失败的问题,只解 API 限流;如果连 git@github.com 都 clone 不下来,那是 SSH key 或网络代理的事,和这个 token 无关。










