从 github npm 注册表安装包 - 身份验证错误 401

Installing packages from github npm registry - auth error 401

我刚刚在 GitHub 上发布了一个私人包,试图弄清楚它应该如何工作。现在我正在尝试将它安装在另一个项目中。我使用具有 write:packagesread:packagesrepo 权限的访问令牌对 npm login --registry=https://npm.pkg.github.com 进行了身份验证。在尝试 运行 npm install https://npm.pkg.github.com/@orgname/package-name 时,我收到一条错误消息:

npm ERR! code E401
npm ERR! Unable to authenticate, need: Basic realm="GitHub Package Registry"

我怎样才能add/get这个特权?

显然我是个白痴,看不懂文档,错过了那部分:

In the same directory as your package.json file, create or edit an .npmrc file to include a line specifying GitHub Packages URL and the account owner. Replace OWNER with the name of the user or organization account that owns the repository containing your project.

registry=https://npm.pkg.github.com/OWNER

除了在 npm 配置中设置注册表之外,您还需要在 Github 上生成个人访问令牌并将其添加到您的 npm 配置中:

  • 在 Github 中导航至 https://github.com/settings/tokens(设置 > 开发人员设置 > 个人访问令牌),您应该会看到如下内容:

  • 点击Generate new token
  • 从权限select至少read:packages

  • 点击Generate token并复制令牌

  • 将以下内容添加到本地 .npmrc:

    @${OWNER}:registry=https://npm.pkg.github.com
    //npm.pkg.github.com/:_authToken=${TOKEN}
    

查看相关内容Github Packages documentation

Related: For Github Actions, be aware of the difference between the GITHUB_TOKEN and a personal access token. The Github Token's permissions are limited to the repository that contains your workflow. For anything else (including granular permissions beyond those allowed for the Github Token) you need a personal access token.

如果您的问题仍然存在,请确保您的包名格式正确。

还有一件事要检查(这花了我一段时间才意识到):

我遇到了指定的错误:

npm ERR! code E401
npm ERR! Unable to authenticate, need: Basic realm="GitHub Package Registry"

尽管我认为我正确地提供了具有所需权限的 GITHUB TOKEN。

我已将我的 github 操作设置为从名为 GPR_PRIVATE_READ_TOKEN 的组织机密中设置 NODE_AUTH_TOKEN,该机密在另一个存储库中工作。

原来 问题是 秘密被定义为仅对私有存储库可用,而我试图在 public 存储库中使用它。当我将秘密提供给 public 个存储库时,一切正常。

我的工作流程看起来像这样(我展示了安装步骤之前的所有步骤,以防有人看到它有帮助):

jobs:
  ci:
    name: Run Tests
    steps:
      - name: Use Node.js 12.x
        uses: actions/setup-node@v1
        with:
          node-version: 12.x
          registry-url: https://npm.pkg.github.com/

      - uses: actions/checkout@v2

      - name: Install dependencies based on package-lock.json
        run: npm ci
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GPR_PRIVATE_READ_TOKEN }}

这对我有用

C:\Program Files\nodejs\node_modules\npm\npmrc

在此处更新文件,您的错误将得到解决

以上 was the solution for me. The updated version is documented as。 此外,我必须确保我的 PAT(个人访问令牌)已获得访问我的组织存储库的授权。