Presently sponsored by: ScriptRunner - Get your free PowerShell Cheat Sheet!

Setting up an entirely new project and getting things off the ground is usually the quickest part of our development process for a project. However, not its not uncommon to stumble into various issues with NuGet, if you're a dotnet dev.

Something I've ran into several times is when running dotnet restore or dotnet add package <name>, the tool throws and error with Unauthorized. Similar to the below message.

dotnet restore
  Determining projects to restore...
  All projects are up-to-date for restore.
DragonFruit -v  0.3.0-alpha.20574.7
  Determining projects to restore...
  Writing C:\Users\tobia\AppData\Local\Temp\tmpE602.tmpinfo : Adding PackageReference for package 'System.CommandLine.DragonFruit' into project 'C:\code\zimmergren.cli\zimmergren.cli.csproj'.
  info : Restoring packages for C:\code\zimmergren.cli\zimmergren.cli.csproj...
  info :   GET
  error: Unable to load the service index for source
  error:   Response status code does not indicate success: 401 (Unauthorized).

Notice how we receive an Unauthorized 401 error on the redacted_org url, which is a private repository that I have access to.

For my new console app, I don't want to pull anything from a private repo. However, the package restore process decides it needs to check the access to the private/protected repository regardless.

Solution 1. Use a NuGet config file.

To work around this, I am creating a new nuget.config file and populating it with the basic content it needs for my project to work.

Should you encounter a more long-term solution to this, please drop a comment or email to share, and I'll be happy to update so more devs can avoid these issues.

Here's the basic nuget.config file that I'm adding to the root of my project:

<?xml version="1.0" encoding="utf-8"?>
    <clear />
    <add key="NuGet Public" value="" />

Immediately after the change, the add and restore commands works, and my development continues.

Solution 2. Verify that your Personal Access Token hasn't expired

If you are pulling packages from private repositories, or you want to solve the problem independently of your specific project, you could look into the tokens you use for the private repositories.

In Azure DevOps, we have something called Personal Access Tokens. In the case of expired tokens, you may also encounter the aforementioned error.

As commented by Tom Brown, refreshing or setting up a new PAT (Personal Access Token) can also be a way to achieve success. Thanks for sharing, Tom.

When you've got a new/regenerated token, you can tell NuGet to make use of the username + token to get access to your private NuGet repository.

nuget.exe sources add -Name "Tobias Private Feed" -Source "https://your-private-repository.url" -username irrelevant -password YOUR_TOKEN_VALUE_HERE

Thanks for reading. These are simple workarounds, but I hope it can save someone the time of troubleshooting.