Search code examples
c#.netnuget-packageuser-secret

grab UserSecrets from a NuGet package


I've written a C# class library for my company to use internally, and it uses DotNet UserSecrets to allow each developer to have their own credentials set without needing to worry about accidentally committing them. It worked fine during testing, but after installing it as a NuGet package as opposed to a project dependency, it no longer seems to be able to read from the secrets.json file. I'm wondering if this is a security thing that C# prevents, or if I need to do something else to enable that functionality in an external package.

The package code looks like this:

using Microsoft.Extensions.Configuration;
using TechTalk.Specflow;

namespace Testing.Utilities
{
    [Binding]
    public class Context
    {
        private static IConfigurationRoot configuration { get; set; }
        private static FeatureContext feature_context;

        // SpecFlow attribute runs this before anything else executes
        [BeforeFeature(Order = 1)]
        private static void SetFeatureContext(FeatureContext context)
        {
            try
            {
                configuration = new ConfigurationBuilder()
                    .AddUserSecrets<Context>()
                    .Build();
            }
            catch { }

            feature_context = context;
            test_context = context.FeatureContainer.Resolve<TestContext>();
        }

        public static string GetSecretVariable(string name)
        {
            object v = null;

            // if the user secrets were found
            if (configuration != null)
            {
                v = configuration[name];
            }

            if (v == null)
            {
                Logger.Warning($"secret variable '{name}' not found");
                return null;
            }

            return v.ToString();
        }
    }
}

And in the calling code which always gets Null from the getter method:

using Testing.Utilities; // via NuGet package

namespace Testing
{
    public static void Main()
    {
       System.Console.WriteLine($"found {Context.GetSecretVariable("super_secret")}");
    }
}

Update: It works as expected when I drag my locally built .nupkg file into my NuGet package cache and replace the one pulled from the repo. I updated the version number and pushed the change so I know they are on the same version, and it still only worked when I manually inserted my build. Now I'm more confused...


Solution

  • I ported the project from .NET Framework 4.6.1 to .NET 6 and it seemed to fix it. Kinda drastic change, but easy enough refactor and 461 is EOL anyways.