ASP. NET Core Elegant Confidentiality in Development Environment (User Secrets)
- 2021-09-24 22:07:19
- OfStack
Preface
In the process of application development, sometimes it is necessary to save some confidential information in the code, such as encryption key, string, or user name and password. The usual practice is to save it to a configuration file. In the past, we would save it to web. config, but in ASP. NET Core, this method may have changed, or you have more diversified methods and more elegant configurations to set up or save these confidential data.
At first, I thought this UserSecrets was useless, because I could configure it directly in appsetting. json file, and I didn't feel its real use until a development process.
Directory
User Confidential Introduction How to Add User Secrets Using User Secrets in Applications SummarizeUser Confidential Introduction
There are the following scenarios that you can think about 1. How we handled it in the previous code:
It is necessary to save 1 key for docking with the third-party website, such as appkey used with WeChat and Weibo sites Configure each developer with an unused username and password to access 1 resources How to configure database addresses, account numbers, and passwords when developers use their own native databases during developmentAssuming that in the last item, each developer uses his own native database, you might say let everyone modify their own web. config, and just don't submit the code when they submit it. Then it is obviously unreasonable not to submit the web. config file when adding other configuration items in web. config.
Now, ASP. NET Core provides a very elegant and concise way to help us solve this problem.
When you create a new ASP. NET Core Web application, you will see this code in the Startup. cs file:
public Startup(IHostingEnvironment env)
{
.....
if (env.IsDevelopment())
{
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
}
In the project. json file, you will see some configurations related to User Secrets
{
"userSecretsId": "aspnet-WebAppCore-e278c40f-15bd-4c19-9662-541514f02f3e"
...
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
"Microsoft.Extensions.SecretManager.Tools": " 1.0.0-preview2-final "
}
You can see the line of builder. AddUserSecrets, which is only running in the development environment.
userSecretsId is used to identify the uniqueness of the project's User Secrets, and if two projects require different Secrets, this requires different userSecretsId.
Microsoft. Extensions. SecretManager. Tools is primarily used to set or view the value of secrets.
How to Add User Secrets
You can use commands on the command line to add:
image
Switch the command line window to the program's running directory and type dotnet user-secrets-h to see the commands available List all user secrets using dotnet user-secrets list Use dotnet user-secrets set WeChatAppKey "X3423FEED2435DD" to set a user secret, where WebChatAppKey is the key followed by the value. Then use dotnet user-secrets list to view the set key-value pair. Then I set a database connection string into it.The above is to use the command line to set user secrets, or you can use Visual Studio 2015 instead of the command line to do this.
In Visual Studio, right-click on the Web project and you will see a menu that manages user secrets:
image
When you click open, a file named secrets. json will appear, which is the key-value pair just set on the command line:
image
Some students may ask, since it is stored in secrets. json, where is this file?
Where is secrets. json stored?
In non-Windows systems, its storage location is in
~/.microsoft/usersecrets/
<
userSecretsId
>
/secrets.json
In the Windows system, it is located in the
C:\ Users\ Username\ AppData\ Roaming\ Microsoft\ UserSecrets\ aspnet-WebAppCore-e278c40f-15bd-4c19-9662-541514f02f3e
As you can see, the upper folder stored is the value set by userSecretsId in the project. json file.
Using User Secrets in Applications
To access configured user secrets in your application, you need to ensure that there are dependencies in the project. json file:
Microsoft. Extensions. Configuration. UserSecrets and builder. AddUserSecrets ().
Then accessed through Configuration object in Startup. cs file
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var wechatKey = Configuration["WeChatAppKey"]
}
You can use DI to map user secrets to an C # class file, like this
secrets.json
{
"SecretsKeys":
{
WeCharAppKey:"xxejfwert3045",
WeboAppKey:"35402345lkefgjlkdfg",
.....
}
}
SecretsKeysConfig.cs
public class SecretsKeysConfig
{
public string WeCharAppKey { get; set;}
public string WeboAppKey { get; set;}
// ......
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SecretsKeysConfig>(Configuration.GetSection("SecretsKeys"));
// Other codes
}
HomeController.cs
public class HomeController : Controller
{
public SecretsKeysConfig AppConfigs { get; }
public HomeController(IOptions<SecretsKeysConfig> appkeys)
{
AppConfigs = appkeys.Value;
}
}
Note: If your appsetting. json file has the same node (conflicting) configuration entry as the secrets. json file, it will be overwritten by the settings entry in secrets. json, since builder. AddUserSecrets () is registered later than AddJsonFile ("appsettings. json"), then we can use this feature to reset the database connection string on each developer's machine.
Summarize
Above, we may feel that Microsoft is very intimate to developers in ASP. NET Core, and many small details are considered. Therefore, in the process of building applications, we can use these small functions (features) to make our code more elegant ~