Nuget 还原 returns 401 在 Jenkins 构建期间未授权用于 Azure DevOps 工件源中的包

Nuget restore returns 401 unauthorized during Jenkins build for packages in Azure DevOps artifacts feed

我们有一个 CI 构建在 Jenkins 中运行。我们在 Azure DevOps 中有一个 NuGet 包提要,在构建期间恢复 NuGet 包时出现 401 Unauthorized 错误:

https://pkgs.dev.azure.com/X/_packaging/FeedName@Release/nuget/v3/index.json: Unable to load the service index for source https://pkgs.dev.azure.com/X/_packaging/FeedName@Release/nuget/v3/index.json. Response status code does not indicate success: 401 (Unauthorized).

詹金斯设置:

我在 Jenkins 机器上安装了 NuGet Credential Provider,但我是在以我自己的身份登录时安装的。我复制了我在笔记本电脑上采取的步骤来解决同样的问题。我的笔记本电脑正在工作。 Jenkins 服务器不是,我认为这与 NuGet Credential Provider 不适用于 "Local System" 帐户有关,但不知道如何解决这个问题。

构建由 PowerShell 脚本控制,NuGet 恢复命令如下所示:

& "$solutionPath"\.nuget\NuGet.exe restore "$solutionFile"

阅读 后,我还通过以下方式向本地 NuGet 安装添加了一个新的 "source":

.\.nuget\NuGet.exe sources add -name "FeedName" -source "https://pkgs.dev.azure.com/X/_packaging/FeedName@Release/nuget/v3/index.json" -username <my username> -password <my personal access token> -configfile .\.nuget\NuGet.config

我试过的用户名:

-password 参数是对 Azure DevOps 工件提要具有 read/write 权限的个人访问令牌的复制和粘贴。

但是,当我这样做时,我作为我的用户名远程进入了 Jenkins 机器,我仍然遇到同样的问题。

如果包来自 Azure DevOps 工件 NuGet 提要,如何在 Jenkins 构建期间恢复 NuGet 包时修复 401 Unauthorized

尝试使用个人访问令牌 (PAT) 的名称作为用户名。这是您在创建 PAT 时为其指定的名称。

编辑 .nuget/NuGet.config 并添加以下代码:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
  <packageSources>
    <add key="MyPackages" value="https://pkgs.dev.azure.com/OrganizationName/_packaging/FeedName@Release/nuget/v3/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <!-- Tag name 'MyPackages' matches 'key' attribute under packageSources -->
    <MyPackages>
      <!-- Username is the name you gave your Personal Access Token in Azure -->
      <add key="Username" value="NameOfPersonalAccessToken" />

      <!-- Choose one of the tags below: -->

      <!-- Use Password if PAT is encrypted -->
      <add key="Password" value="EncryptedPersonalAccessTokenGoesHere" />

      <!-- Use ClearTextPassword if PAT is encrypted -->
      <add key="ClearTextPassword" value="PlainTextPersonalAccessTokenGoesHere" />
    </MyPackages>
  </packageSourceCredentials>
</configuration>

更多信息:https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file#packagesourcecredentials