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

npm v8迁移至v9后发布Nexus遇E401认证错误求助

问题:npm v9迁移后发布到Nexus出现401认证失败

迁移背景

从Node.js 16.19.1(配套npm 8.19.1)迁移至Node.js 20.5.1(配套npm 9.8.0),需将npm包发布至版本为OSS 3.41.1的Nexus仓库。

原npm v8.19.1有效配置

npm config set registry="http://nexus.example.com:8081/nexus/repository/example-package/"
npm config set _auth="MY_BASE_64_TOKEN"
npm config set email="my.project@mail.com"
npm config set always-auth=true
npm config set strict-ssl=false

npm v9的破坏性变更

  • always-auth不再是全局有效配置项
  • _auth不能作为全局配置,必须绑定到具体的Registry URL
  • auth-type默认值从legacy改为web

修改后的npm v9配置

npm config set email="my.project@mail.com"
npm config set strict-ssl=false
npm config set auth-type=legacy
npm config set registry="http://nexus.example.com:8081/nexus/repository/example-package/"
npm config set //nexus.example.com:8081/nexus/repository/example-package/:_auth=MY_BASE_64_TOKEN

执行npm publish时的错误

npm verb Linux 5.15.0-1041-azure
npm verb node v20.5.1
npm verb npm  v9.8.0
npm ERR! code E401
npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
npm verb exit 1
npm verb code 1

解决方法

1. 给目标Registry单独添加always-auth配置

虽然全局always-auth被移除,但npm v9支持针对单个Registry设置该选项,补上这条配置:

npm config set //nexus.example.com:8081/nexus/repository/example-package/:always-auth=true

2. 验证Auth Token的正确性

确保MY_BASE_64_TOKEN是username:password格式的字符串经过Base64编码后的结果,本地可以用echo "MY_BASE_64_TOKEN" | base64 -d解码检查是否符合格式。

3. 调整配置顺序

先设置Registry相关的认证项,再设置全局配置,避免潜在的优先级问题:

# 先绑定Registry的认证信息
npm config set //nexus.example.com:8081/nexus/repository/example-package/:_auth=MY_BASE_64_TOKEN
npm config set //nexus.example.com:8081/nexus/repository/example-package/:always-auth=true
# 再设置全局和Registry地址
npm config set registry="http://nexus.example.com:8081/nexus/repository/example-package/"
npm config set email="my.project@mail.com"
npm config set strict-ssl=false
npm config set auth-type=legacy

4. 改用环境变量传递配置(GitHub Actions推荐)

在GitHub Actions的工作流中,直接通过环境变量传递配置更稳定,避免命令行设置的冲突:

env:
  NPM_CONFIG_REGISTRY: http://nexus.example.com:8081/nexus/repository/example-package/
  NPM_CONFIG_EMAIL: my.project@mail.com
  NPM_CONFIG_STRICT_SSL: false
  NPM_CONFIG_AUTH_TYPE: legacy
  # 注意Registry地址部分要全大写,特殊字符替换为下划线
  NPM_CONFIG_//NEXUS.EXAMPLE.COM:8081/NEXUS/REPOSITORY/EXAMPLE-PACKAGE/:_AUTH: ${{ secrets.MY_BASE_64_TOKEN }}
  NPM_CONFIG_//NEXUS.EXAMPLE.COM:8081/NEXUS/REPOSITORY/EXAMPLE-PACKAGE/:ALWAYS_AUTH: true

5. 检查Nexus仓库权限

确认用于认证的账号拥有该Nexus仓库的发布权限:

  • 登录Nexus后台,找到example-package仓库
  • 给对应账号分配nx-repository-view-npm-example-package-*权限(至少包含add和edit权限)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:08:34