Take advantage of user secrets management in ASP.NET Core to prevent the sharing of sensitive application data in your projects Credit: Thinkstock When working with ASP.NET web applications, you will want to protect certain pieces of application data, called user secrets, that should not be shared with others. Your user secrets might include a database connection string that also contains the user ID and the password for the database. You might also want to refrain from sharing information such as access keys, API keys, and connection information details for cloud services such as Azure or AWS. However, when you share your project with others this secret information also will be shared. How can we prevent this? A feature in ASP.NET Core named User Secrets allows you to store user secrets outside your project tree in a JSON file, and can even be managed using a command-line tool called the Secrets Manager. This article talks about how you can work with the User Secrets API in ASP.NET Core. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core MVC project in Visual Studio 2019 First off, let’s create an ASP.NET Core project in Visual Studio 2019. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Create. In the “Create a New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 3.1 (or later) from the drop-down list at the top. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either. Click Create. Following these steps will create a new ASP.NET Core MVC project in Visual Studio 2019. We’ll use this project in the sections below to illustrate how we can manage user secrets in our ASP.NET Core 3.1 projects. Add user secrets management to your project Adding user secrets management to your project is fairly straightforward. All you need to do is select the project in the Solution Explorer window, right-click on the project, and then select Manage User Secrets as shown in Figure 1 below. IDG Figure 1 This will open the secrets.json file in your Visual Studio IDE. Here’s where you can add your secrets as shown below. { "ConnectionString": "This is a test connection string", "APIKey": "This is s secret key", "AppSettings": { "GlobalSettings": { "GlobalAccessKey": "This is a global access key!" } } } The secret.json file is created at the following location: C:UsersjoydipAppDataRoamingMicrosoftUserSecretse4f51d14-ddc1-48f4-bb34-84c114e3d6d0 When you open the .csproj file of your project, you’ll notice that a UserSecretsId element has been added as shown in the code snippet given below. <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <UserSecretsId>e4f51d14-ddc1-48f4-bb34-84c114e3d6d0</UserSecretsId> </PropertyGroup> </Project> Use the Secret Manager tool in .NET Core The Secret Manager tool is a command-line tool available in .NET Core for managing your configuration and secret data. In this section we’ll examine how we can work with this tool. Enable user secrets Type the following command at the command prompt: dotnet user-secrets init Set a secret To list the available secrets, you can use this command: dotnet user-secrets list Figure 2 below shows the list of keys we created earlier. IDG Figure 2 You can use the following command to set a key: dotnet user-secrets set "AuthorApiKey" "xyz1@3" Access a secret To access user secrets programmatically, you can take advantage of the Configuration API in ASP.NET Core. Let’s update the HomeController class to be able to access the configuration data. At first glance, the HomeController class would look like this: public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } //Action methods go here - this is done for brevity } The following code snippet illustrates how we can update the HomeController class and leverage dependency injection to be able to inject an instance of IConfiguration using constructor injection. public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IConfiguration _config; public HomeController(ILogger<HomeController> logger, IConfiguration config) { _logger = logger; _config = config; } //Action methods go here - this is done for brevity } Remove a secret To remove a key, you can use the following command: dotnet user-secrets remove "AuthorApiKey" If you want to remove all keys, you can use the following command instead: dotnet user-secrets clear Here is a variation on the same command that removes GlobalSettings from the stored secrets: dotnet user-secrets remove "AppSettings:GlobalSettings" The ability to configure, manage, and secure configuration data has been redefined in ASP.NET Core. User Secrets is a great feature in ASP.NET Core that is an excellent alternative to using environment variables. User Secrets ensures that there is no sensitive data included in the source code. Instead, the user secrets are stored outside of the project folder — inside the user’s profile folder in the file system. However, one downside is that the data that is stored by User Secrets is not encrypted. I will discuss other options for protecting user secrets such as Azure application settings and Azure key vault in a future article here. How to do more in ASP.NET Core: How to build gRPC applications in ASP.NET Core How to redirect a request in ASP.NET Core How to use attribute routing in ASP.NET Core How to pass parameters to action methods in ASP.NET Core MVC How to use API Analyzers in ASP.NET Core How to use route data tokens in ASP.NET Core How to use API versioning in ASP.NET Core How to use Data Transfer Objects in ASP.NET Core 3.1 How to handle 404 errors in ASP.NET Core MVC How to use dependency injection in action filters in ASP.NET Core 3.1 How to use the options pattern in ASP.NET Core How to use endpoint routing in ASP.NET Core 3.0 MVC How to export data to Excel in ASP.NET Core 3.0 How to use LoggerMessage in ASP.NET Core 3.0 How to send emails in ASP.NET Core How to log data to SQL Server in ASP.NET Core How to schedule jobs using Quartz.NET in ASP.NET Core How to return data from ASP.NET Core Web API How to format response data in ASP.NET Core How to consume an ASP.NET Core Web API using RestSharp How to perform async operations using Dapper How to use feature flags in ASP.NET Core How to use the FromServices attribute in ASP.NET Core How to work with cookies in ASP.NET Core How to work with static files in ASP.NET Core How to use URL Rewriting Middleware in ASP.NET Core How to implement rate limiting in ASP.NET Core How to use Azure Application Insights in ASP.NET Core Using advanced NLog features in ASP.NET Core How to handle errors in ASP.NET Web API How to implement global exception handling in ASP.NET Core MVC How to handle null values in ASP.NET Core MVC Advanced versioning in ASP.NET Core Web API How to work with worker services in ASP.NET Core How to use the Data Protection API in ASP.NET Core How to use conditional middleware in ASP.NET Core How to work with session state in ASP.NET Core How to write efficient controllers in ASP.NET Core Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos