我们正在使用Cake Build自动化构建,同时使用来自nuget.org的NuGet包,但我们还有自己的NuGet Feed服务器,需要用户名/密码进行身份验证才能访问。如何在自定义带有身份验证的NuGet Feed服务器上使用Cake Build?
我们正在使用Cake Build自动化构建,同时使用来自nuget.org的NuGet包,但我们还有自己的NuGet Feed服务器,需要用户名/密码进行身份验证才能访问。如何在自定义带有身份验证的NuGet Feed服务器上使用Cake Build?
nuget sources Update -Name [name of source] -Source [uri to your source] -UserName [your username] -Password [your password]
免责声明:一些版本的NuGet.exe
和dotnet CLI存在加密密码的问题,解决方法是像这样添加-StorePasswordInClearText
:
nuget sources Update -Name [name of source] -Source [uri to your source] -UserName [your username] -Password [your password] -StorePasswordInClearText
那么你的凭据会以明文形式保存,这种方式的缺点在于你的凭据会以明文形式保存。
你还可以通过为#tool
/#addin
指令和NuGet别名指定特定源来覆盖nuget.config
设置。
下面是一个例子,用于说明提供#tool
指令的来源:
#tool "NUnit.ConsoleRunner"
or
#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0
成为
#tool nuget:[source]?package=NUnit.ConsoleRunner
or
#tool nuget:[source]?package=NUnit.ConsoleRunner&version=3.4.0
即官方V2 NuGet源
#tool nuget:https://www.nuget.org/api/v2?package=NUnit.ConsoleRunner
or
#tool nuget:https://www.nuget.org/api/v2?package=NUnit.ConsoleRunner&version=3.4.0
下面是一个示例,说明如何为#addin
指令提供源代码。
#addin "Cake.Slack"
or
#addin nuget:?package=Cake.Slack&version=0.4.0
变成
#addin nuget:[source]?package=Cake.Slack
or
#addin nuget:[source]?package=Cake.Slack&version=0.4.0
即为官方V2 NuGet feed。
#addin nuget:https://www.nuget.org/api/v2?package=Cake.Slack
or
#addin nuget:https://www.nuget.org/api/v2?package=Cake.Slack&version=0.4.0
NuGet 别名 包括类似 NuGetAddSource 和 NuGetHasSource 的命令,用于直接处理源,如果您例如希望在 NuGet 恢复步骤之前将源添加到 CI 中,则非常实用:
var source = new {
Name = EnvironmentVariable("PRIVATE_FEED_NAME"),
Source = EnvironmentVariable("PRIVATE_FEED_SOURCE"),
ApiUserName = EnvironmentVariable("PRIVATE_FEED_USERNAME"),
ApiKey = EnvironmentVariable("PRIVATE_FEED_PASSWORD")
};
if (!NuGetHasSource(source.SourceUrl))
{
NuGetAddSource(
source.Name,
source.SourceUrl,
new NuGetSourcesSettings {
UserName = source.ApiUserName,
Password = source.ApiKey
}
);
}
以上内容仅会将源添加到您现有的nuget.config
,但您还可以覆盖NuGetInstall和NuGetRestore别名的NuGet源。
NuGetInstall别名具有多个重载,其中包含一个NuGetInstallSettings工具设置类,其中有一个Source属性,您可以使用它来覆盖使用哪些源,例如:
NuGetInstall("MyNugetPackage", new NuGetInstallSettings {
Source = new []{ "https://api.nuget.org/v3/index.json" }
});
类似地,NuGetRestore别名有多个重载,可以让您指定一个NuGetRestoreSettings,该设置具有Source属性,您可以使用它来覆盖所使用的源,例如:
var solutions = GetFiles("./**/*.sln");
// Restore all NuGet packages.
foreach(var solution in solutions)
{
Information("Restoring {0}", solution);
NuGetRestore(
solution,
new NuGetRestoreSettings {
Source = new []{ "https://api.nuget.org/v3/index.json" }
}
);
}
有几种方法可以解决您的问题。
如果您在计算机上配置了多个源,也可以通过指定源来获得更好的NuGet还原/安装性能,但当前项目仅使用官方源,因此会跳过查找所有已配置的源并直接进入源。
但如果您的源需要身份验证,则需要使用nuget.exe
或NuGetAddSource别名为其添加凭据。
对于那些使用MyGet的人,它有预验证的url供您在不添加源的情况下使用,只需为还原/安装指定Source属性即可。这是敏感信息,因此不要将它们存储在构建脚本中,而应将它们作为环境变量存储。