I am trying to download packages from a Nuget repository which requires credentials for it to be accessed using NuGet.Core.
I know that Nuget repositories with no authentication can be accessed as follows:
//ID of the package to be looked up
string packageID = "EntityFramework";
//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
//Initialize the package manager
string path = <PATH_TO_WHERE_THE_PACKAGES_SHOULD_BE_INSTALLED>
PackageManager packageManager = new PackageManager(repo, path);
//Download and unzip the package
packageManager.InstallPackage(packageID, SemanticVersion.Parse("5.0.0"));
(source: Nuget blog)
Now suppose I have the credentials of a Nuget repository. I tried to get the package using http client and network credentials but it did not work. So how do I pass the credentials along to the Nuget server?
Also I would like to know how to restrict access to a Nuget feed(what do newer versions offer?).
I can't seem to find any clear documentation.
Thanks.
I am assuming you are using NuGet 2.x and not NuGet 3.0.
In order for NuGet to send credentials to a server you need to configure the DefaultCredentialProvider on NuGet's HttpClient class.
HttpClient.DefaultCredentialProvider = new YourCredentialProvider ();
NuGet provide a SettingsCredentialProvider class which will try to find username's and password's in the user's NuGet.Config file but you still need to implement your own ICredentialProvider since the SettingsCredentialProvider requires one to be passed to its constructor. It uses this credential provider typically to prompt the user to enter credentials.
HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new ConsoleCredentialProvider(Console), SourceProvider, Console);
NuGet provides a ConsoleCredentialProvider which you could use. It also provides a Console and a way to create a source provider.
To restrict access to your own NuGet server you can use the NuGet.Server NuGet package and create your own web app. Then you can host that on IIS and use the standard IIS authentication features.
An alternative is to use a third party hosting service such as MyGet which allows you to setup private feeds that require authentication.