You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Github Actions安装私有npm包遇401未授权问题求助

解决GitHub私有npm包安装401未授权问题

问题场景

同一组织下的私有GitHub项目使用GitHub npm仓库,已配置项目根目录的.npmrc:

@organization:registry=https://npm.pkg.github.com
registry=https://registry.npmjs.org

always-auth=true
save-exact=true

CI环节通过GitHub Actions执行依赖安装,但即使使用了全权限的ADMIN_TOKEN,仍报错:

npm error code E401
npm error 401 Unauthorized - GET https://npm.pkg.github.com/@organization%2fpackage - authentication token not provided

解决步骤

1. 修正CI中的token配置方式

手动执行npm config set可能因环境变量优先级或配置路径问题不生效,推荐直接向.npmrc追加认证信息:

- name: Setup Node
  uses: actions/setup-node@v4
  with:
    node-version: 22.x
    cache: 'npm' # 可选,加速依赖安装

- name: 配置GitHub Packages认证
  run: |
    # 向项目根目录的.npmrc追加token配置
    echo "//npm.pkg.github.com/:_authToken=${{ secrets.ADMIN_TOKEN }}" >> .npmrc

或者修改用户目录的.npmrc(全局生效):

- name: 配置GitHub Packages认证
  run: echo "//npm.pkg.github.com/:_authToken=${{ secrets.ADMIN_TOKEN }}" >> ~/.npmrc

2. 验证ADMIN_TOKEN的权限

确保ADMIN_TOKEN是个人访问令牌(PAT),并勾选以下必要权限:

  • read:packages:必须,用于拉取私有npm包
  • repo:若私有包所在仓库为私有,需此权限访问仓库内容

3. 排查.npmrc的最终生效内容

在CI中添加调试步骤,确认认证配置是否正确加载:

- name: 调试.npmrc配置
  run: |
    echo "用户目录.npmrc内容:"
    cat ~/.npmrc
    echo "项目根目录.npmrc内容:"
    cat .npmrc

最终生效的.npmrc需同时包含组织registry和对应token:

@organization:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=你的ADMIN_TOKEN
registry=https://registry.npmjs.org
always-auth=true
save-exact=true

4. 改用npm ci优化CI环境安装

npm ci严格按照package-lock.json安装,更适合CI环境,避免版本差异导致的问题:

- name: 安装依赖
  run: npm ci

内容的提问来源于stack exchange,提问作者baitendbidz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:27:14