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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos