Learn ASP.NET Core 3.0 : MVC, Razor Pages, Web API, Entity Framework Core, and Blazor.
Microsoft's official documentation can be found here. Looking for professional online training courses? Next weekend batches are starting in November 2019. More details here.

Create and Use User Secrets in ASP.NET Core

While developing an ASP.NET Core web application you often come across pieces of information that you wouldn't like to share with others. Consider, for example, a database connection string that contains a user ID and password. You typically store it in appsettings.json file. But when you share your project code with others (say through a version control system) those details are also shared with others. Another example could be access keys or API keys. You might not want to share these details with others. Luckily, ASP.NET Core and Visual Studio provide an easy way to deal with this requirement through what is known as User Secrets.

User secrets are pieces of information that aren't stored in your Visual Studio project structure. They are stored in a file named secrets.json that resides inside :

%APPDATA%\Microsoft\UserSecrets\secrets.json 

Since secrets.json is stored outside your project folder it's not shared with others. When you run your application on your machine, Visual Studio grabs the secrets.json file and merges it with the appsettings.json. You can then read the secrets just like you normally read settings from appsettings.json. Note that User Secrets is only a development time feature.

Now that you know what User Secrets are let's see how to work with them in Visual Studio.

Create a new ASP.NET Core MVC application using Visual Studio. Then right click on the project in Solution Explorer and click on Manage User Secrets shortcut menu option.

This will open secrets.json file in the Visual Studio IDE. Add the following JSON markup to the file and save it.

{
  "SecretKey1": "Hello World!",
  "SecretKey2": "Hello Galaxy!",
  "AppSettings": {
    "GlobalSettings": {
      "SecretKey3": "Hello Universe!"
    }
  },
  "AppSettings:GlobalSettings:SecretKey4": 
                      "Hello ASP.NET Core!"
}

There are four keys stored in secret.sjon - SecretKey1, SecretKey2, SecretKey3, and SecretKey4. The SecretKey3 is nested inside AppSettings:GlobalSettings section. Instead of nesting a key in this manner, you can also flatten it as shown for the SecretKey4 key.

Now, open appsettings.json file and add a key there:

"SecretKey2": "Hello!"

We add this duplicate SecretKey2 key just to confirm that value from settings.json takes precedence.

Next, open Visual Studio *.csproj file of the project. You will find that a UserSecretsId element gets added to it as shown below:

<PropertyGroup>
  <TargetFramework>netcoreapp3.0</TargetFramework>
  <UserSecretsId>
       7eaa2cdf-679f-4367-a9ea-203f207c565f
  </UserSecretsId>
</PropertyGroup>

You will also notice that secret.json is created in the following location:

\Users\User_Name_Here\AppData\Roaming\Microsoft\
UserSecrets\7eaa2cdf-679f-4367-a9ea-203f207c565f

Ok. Now let's access these setting from the HomeController. Add the following constructor to the HomeController:

public HomeController(IConfiguration config)
{
    this.config = config;
}

As you can see, we have injected the IConfiguration object into the controller so that we can access the configuration settings.

Then write this code to read the secret keys and store them in the ViewBag:

public IActionResult Index()
{
    ViewBag.SecretKey1 = config["SecretKey1"];
    ViewBag.SecretKey2 = config["SecretKey2"];
    ViewBag.SecretKey3 = 
config["AppSettings:GlobalSettings:SecretKey3"];
    ViewBag.SecretKey4 = 
config["AppSettings:GlobalSettings:SecretKey4"];

    return View();
}

As you can see, the code accesses the secret keys as if they are part of appsettings.json. Since key-values from secret.json are merged with appsettings.json you get the correct values in the ViewBag properties. Also, note that value of SecretKey2 from secret.json takes precedence over the value from appsettings.json. The following figure shows a sample run of the application.

The .NET Core provides user-secrets CLI tool that can be used to manipulate secrets.json file. You may read more about the tool here.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn

Posted On : 10 June 2019


Tags : ASP.NET ASP.NET Core .NET Framework C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates