使用Docker映像中的"dotnet"测试Nuget Auth凭据



如果提供的凭据无效,我正在寻找一种安全而直接的方法来使图像构建失败。问题是,我需要从中提取包的回购有一个策略,该策略在多次尝试失败后锁定帐户——由于每个包都算作单独的身份验证尝试,一次错误的构建尝试将锁定帐户。

在我的Dockerfile中,我像这样设置nuget源,然后像这样恢复(或发布/运行等(。

RUN dotnet nuget add source https://my-example-repo.jfrog.io/my-example/api/nuget/nuget  
-n Artifactory 
-u ${JFROG_USERNAME} 
-p ${JFROG_PASSWORD} 
--store-password-in-clear-text
RUN dotnet restore 

理想的解决方案是两件事之一:

  1. dotnet restore的标志,如果任何程序包无法恢复,该标志将立即以非零代码退出,例如dotnet restore --failfast
  2. 一个单一的、安全的、幂等的命令,用于使用当前凭据进行身份验证,如果凭据不起作用,则退出非零

它看起来有点粗糙,但我建议使用这样的方法。

您可以简单地创建一个测试C#项目,其中包含对私有存储库中包的一个引用。

然后尝试通过dotnetCLI进行恢复。

如果您的凭据无效,它将失败,并且会有一个非零的退出代码。


  1. 使用凭据配置NuGet源

如您所知,当您运行dotnet restore时,它使用一种特殊的机制来累积不同级别的设置:

  • 解决方案
  • 用户
  • 计算机

Microsoft文档/通用NuGet配置

因此,运行此命令时,会更新用户nuget.config文件。

(在Windows上,它位于%APPDATA%NuGetnuget.config(

dotnet nuget add source https://my-example-repo.jfrog.io/my-example/api/nuget/nuget  
-n Artifactory 
-u ${JFROG_USERNAME} 
-p ${JFROG_PASSWORD} 
--store-password-in-clear-text
  1. 创建一个名为credentials-test.csproj的测试项目文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<!-- Replace an example by your package from private repository. -->
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" />
</ItemGroup>
</Project>
  1. 然后只需运行dotnet restore命令:
dotnet restore .credentials-test.csproj

如果凭据有效,PowerShell中的结果将是:

> dotnet restore .credentials-test.csproj
Determining projects to restore...
Restored C:Projectsnuget-restore-2credentials-test.csproj (in 340 ms).
> $LastExitCode
0

如果凭证无效或任何其他故障,结果将是:

> dotnet restore .credentials-test.csproj
Determining projects to restore...
<SOME ERROR MESSAGE>
> $LastExitCode
1 <-- Or some different non-zero exit code

看起来不太好看。但有效。


为了好玩,我花了一些时间实现了一个.NET CLI工具,为您提供了一个CLI命令。然而,这比上面描述的想法更糟糕。

你可以在这里查看:https://youtu.be/SanQAVAZM2o

最新更新