Search code examples
authentication.net-coreazure-devopsnugetdotnet-cli

Adding PackageReference for package fails with 401 (Unauthorized)


I am trying to install a third-party NuGet package (e.g. StyleCop) into a project. The project also has packages that are installed from our own private NuGet feed. When trying to install the package, we receive a 401 error like this.

MyProject> dotnet add .\MyProject.csproj package StyleCop
  Determining projects to restore...
  Writing C:\Users\me\AppData\Local\Temp\tmp6A51.tmp
info : Adding PackageReference for package 'StyleCop' into project '.\MyProject.csproj'.
info :   CACHE https://api.nuget.org/v3/registration5-gz-semver2/stylecop/index.json
info :   GET https://mediavaletsc.pkgs.visualstudio.com/_packaging/c559332f-5d8d-4d3f-8fc2-6e06125775fa/nuget/v3/registrations2-semver2/stylecop/index.json
info :   Unauthorized https://mycompany.pkgs.visualstudio.com/_packaging/xxx-xxx-xxx-xxx-xxx/nuget/v3/registrations2-semver2/stylecop/index.json 680ms
error: Response status code does not indicate success: 401 (Unauthorized).

Oddly enough, running dotnet restore works just fine, even after doing a git clean -xfd. How can we configure dotnet and/or nuget to accept the installation of StyleCop or any other public package?


Solution

  • We needed to re-authenticate with Visual Studio Team Services (VSTS) because the API key had expired and/or been revoked.

    The reason dotnet restore still worked, but dotnet add ... package ... failed, was because the former used the local cache, whereas the latter hit the server. Restore also stopped working after we ran nuget locals all -clear.

    To re-authenticate with did the following.

    nuget sources remove -name $sourceName | Out-Null;
    nuget sources add -name $sourceName -source $sourcePath -username $username -password $apiKey