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

GitHub Actions安装私有包时遭遇401未授权错误排查求助

GitHub Actions中npm install报E401认证错误的排查与解决

问题场景

执行GitHub Actions工作流的npm install --legacy-peer-deps步骤时,触发以下认证错误:

npm ERR! code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"

已通过release.yml配置创建.npmrc文件,并使用GitHub Secrets注入认证令牌,但问题仍未解决。工作流片段如下:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: latest

      - name: Create .npmrc
        run: |
          echo "@***:registry=https://***" > .npmrc
          echo "@***:registry=https://***" >> .npmrc
          echo "@***:registry=https://***" >> .npmrc
          echo "registry=https://registry.npmjs.org" >> .npmrc
          echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_ACCESS_KEY }}" >> .npmrc
          echo "always-auth = true" >> .npmrc

      - run: ls -ail
      - run: npm version
      - run: npm install --legacy-peer-deps
      - run: npm run build-web:prod release

错误原因

报错明确指向Sonatype Nexus仓库的BASIC认证失败,但当前.npmrc仅配置了npm官方源的认证令牌,那三个私有域(@***)对应的Nexus仓库未添加任何认证信息。当npm拉取这些私有域的包时,无法通过Nexus的身份校验,因此抛出E401错误。

解决方法

1. 为Nexus私有源添加认证配置

针对每个指向Nexus的私有域,在.npmrc中补充对应的认证信息:

  • 如果Nexus支持令牌认证,修改Create .npmrc步骤(替换为你的Nexus仓库地址和Secrets名称):
    - name: Create .npmrc
      run: |
        echo "@scope1:registry=https://your-nexus-repo-url" > .npmrc
        echo "@scope2:registry=https://your-nexus-repo-url" >> .npmrc
        echo "@scope3:registry=https://your-nexus-repo-url" >> .npmrc
        # 添加Nexus仓库的令牌认证
        echo "//your-nexus-repo-url/:_authToken=${{ secrets.NEXUS_AUTH_TOKEN }}" >> .npmrc
        echo "registry=https://registry.npmjs.org" >> .npmrc
        echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_ACCESS_KEY }}" >> .npmrc
        echo "always-auth = true" >> .npmrc
    
  • 如果Nexus仅支持账号密码的BASIC认证,先将用户名:密码进行Base64编码,再写入.npmrc:
    echo "//your-nexus-repo-url/:_auth=<base64编码后的用户名密码>" >> .npmrc
    

2. 验证.npmrc配置正确性

在npm install步骤前添加命令,检查.npmrc的内容(避免泄露敏感令牌):

- run: cat .npmrc | grep -v "_authToken"

确认所有私有源的registry地址和认证配置行都已正确生成。

3. 检查GitHub Secrets配置

确认仓库的Secrets中已正确添加NEXUS_AUTH_TOKEN(或对应密码的Base64字符串),且该令牌/账号拥有拉取Nexus对应私有包的权限。

4. 确认Nexus仓库的认证规则

登录Nexus后台,检查目标仓库的认证策略:是否允许令牌访问、是否需要特定权限组,确保你的认证信息符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:52:05