ASP.NET Core User Secrets Getting Started

Introduction

Developers, regardless of their specialization or favorite framework. In most cases, they continuously build and use a configuration that will access during runtime.

This configuration could be a database connection string, API keys, user-specific settings (which are highly confidential in most cases), or other key-value pair settings that are sensitive pieces of information.

It is not good to put your configuration settings around in our source code and later deploy to a production server or a repository like GitHub.

Moreover, this information should be protected, in my opinion, because there is a chance that we might give someone unauthorized access.

Any sensitive data is an app secret. App secret should be stored elsewhere from your project.

That's why in this article, we'll explore app secrets in .NET core.

OK, let's get started.

Background

Before we start the tutorial, just a heads up. I'll be using Visual Studio 2022, and I'll be creating an ASP.NET Core Web App. From that, I'll start showing and making app secrets within Visual Studio.

Open your Visual Studio, and let's create an ASP.NET Core Web App, just follow the steps below.

If you believe you already know these steps, you can jump to the next section. Otherwise, continue reading.

Setting Up App Secrets

There are two ways we can manage user secrets in our application. The first one is the manual approach, and the second one uses the command dotnet user-secrets, and we'll focus more on using this command.

Initialize App Secrets

After creating an ASP.NET Core Web Application, let's start by initializing our user secrets via Developer PowerShell by typing the command.

dotnet user-secrets init --project UserSecrets

As you can see, I've passed my own local project name to the --project parameter. If you decide to create your own VS project, just give the name of your project.

Once the command has finished, it will generate a new directory with a GUID style as the directory's name.

After this command, you'll also see that your *.csproj file will have the GUID user secrets stored as part of the project configuration.

If you want to locate the path of the generated secrets.json, you can open it via Windows Explorer.

Just type without the quotes "%appdata%\Microsoft\UserSecrets\" in my case it would be “%appdata%\Microsoft\UserSecrets\aefce3b6-5896-4a6a-b4b4-7e1556dc434e”.

Lastly, if you want to see the file inside VS, just right-click on the project, then choose "Manage User Secrets."

Note: If you don't want to interact with the command line, you can just right-click on your project and select "Manage User Secrets" to initialize the user secrets for you. You can manually input the configuration settings inside VS.

Setting and Showing App Secrets

We need to set up our dummy connection strings this time.

Let's see how we can do it.

dotnet user-secrets set "connectionstrings" "this is my connectionstring" --project UserSecrets

Great! Let's try to see the user secrets that we have.

dotnet user-secrets list --project UserSecrets

I know the value that we have doesn't make any sense. So what we can do now is update the connection strings.

dotnet user-secrets set "connectionstrings", "Data Source=(localhost);Initial Catalog=northwind;Integrated Security=true" --project UserSecrets

Accessing App Secrets Inside Your ASP.NET Web Project

In our case, I'm using ASP.NET Core Web App that uses Razor web pages, it may not be exactly yours, but the concept is the same.

Let's try to see the code below.

Index.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace UserSecrets.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        /*added the IConfiguration here so we can access the user secrets*/
        private readonly IConfiguration _configuration;

        public string ConnectionString { get; private set; }

        public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
        {
            _logger = logger;
            /*initialize here when this instance started*/
            _configuration = configuration;
        }

        public void OnGet()
        {
            /*set here the ConnectionString value*/
            ConnectionString = this._configuration["connectionstrings"];
        }
    }
}

Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <!-- container -->
    <div class="w-80 border">
        <h4>My ConnectionString From UserSecrets</h4>
        <!-- show connectionstrings here-->
       <div>@Model.ConnectionString</div> 
    </div>
    <!-- end of container-->
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

Output

 

What we actually did is we used the IConfiguration and made it part of the IndexModel class.

Then we initialize it on the constructor part of the IndexModel class and set it on the OnGet method.

After selecting the ConnectionString property, we have decided to display it on the markup/HTML page. That's it, and it is so easy, isn't it?

Summary

This article has discussed setting up app secrets for our project.

Moreover, we have shown how to initialize, list, update and access our web project.

I hope you have enjoyed this article as I have enjoyed writing it.

Stay tuned for more. Until next time, happy programming!

Please don't forget to bookmark, like, and comment. Cheers, and Thank you!