Hello everyone, I'm Zhang Anzhong, a researcher at Microsoft's MVP Lab in this issue. Today I will show you how to use the Azure Key Vault feature integrated in ASP.NET Core and Java projects through experiments and a complete operation process.
Analysis of ideas
In software development, project security is the top priority, especially in multi-department or open source projects, how to save our keys without affecting local development is a problem that our developers need to consider. Here is a brief list of the solutions we do in our usual development:
- Local development is directly in the form of localhost. Whether it is DB or ES/Redis/MQ, or others, all use local parameters, and then use Configmap to mount when deploying to K8s. is also a solution, but it will make the isolation between dev and prod more severe.
- Use a remote configuration center to unify local and production-direct data. For example, the common ones are Apollo, Azure's Key Vault technology, and so on. Recommended way
- Manually modify it every time you go online. This is clearly unreasonable
PS: This article uses 21Vianet's azure.cn .
Preliminary account preparation
First, you need to register an Azure account.
Secondly, you need to register an application. When registering, fill in the Client password. The password should be saved well, and it will be used many times in the future.
Search for app registration and register an account:
Enter the application name, the others are default:
Next, in Certificates & secrets, add Client secrets:
With an app, it's possible to set keys within the app.
this time, we already have two parameters, ClientId and ClientSecret .
Configure key vault
Step 1 - Add Key vault service
Go ahead and search for the Key vault keyword at the top:
Create a brand new key vault service, choose your own subscription and resource group, and set the following name:
After the creation is complete, you can see the other two parameters on the overview page of the key vault:
two other parameters, one is the uri of the vault, and the other is the . 161d97ccb132d8 is also ready.
At this point, the four parameters are all ready.
Step 2 - Parameter Settings
Click the secrets option under settings to create or import a configuration:
In the new page that pops up, select the Manual mode, enter the name and value, and configure the user name of the database:
Then the creation is complete, you can also configure the sqlserver password by imitating:
Step 3 - Access Policy Settings
After the creation is complete, click to go to the resource to configure the access policy, "Settings="Access policies", click "Add Access Policy" to create a new access policy.
First select the configuration template Configure from template (optional): "Secret Management".
Click "Nono select" to select the service subject first, enter "your own service account name", such as laozhang.keyvault.demo, select it, click "Select", and save it.
At this point, the configuration related to Azure has been completed, let's start writing code.
Create a new Core project
Step 1 - Create an ASP.Net Core5.0 API project
The process is very simple, so I won't say more. After creating it, add the nuget package:
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.21" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />
Then, put the above four variables into the environment variables, and local development can be in launchSettings.json:
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"AZURE_TENANT_ID": "你的tenantid",
"AZURE_CLIENT_ID": "你的客户端id",
"AZURE_CLIENT_SECRET": "你的客户端密钥",
"AZURE_KEY_VAULT_URI": "https://blog-core-keyvault.vault.azure.cn/"
}
}
Step 2 - Configure Program, connect to Configuration Center
Configure in Program.cs:
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
var clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
config
.AddJsonFile("appsettings.json", true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
string vaultUri = "https://blog-core-keyvault.vault.azure.cn/";
config.AddAzureKeyVault(vaultUri, clientId, clientSecret);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
If there is no error when starting the application at this time, congratulations, the connection has been successful, and the next step is to obtain the specified parameters.
Step 3 - Get the value of the Key Vault anywhere
The method of use here is exactly the same as that in the ordinary appsettings.json, just inject the configuration:
_configuration.GetValue<string>("MSSQL-USER-PASSWORD");
Well, in the ASP.NET Core application, the connection to the Azure Key Vault has been finished, let's see how Java operates.
Create a new Java project
Step 1 - Create a Spring Boot project
The process is also very simple, you can create it with Idea, or you can use the official template to create it. I won't say much. After creating it, add the pom package:
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>azure-spring-boot-starter-keyvault-secrets</artifactId>
</dependency
Then, put the above four variables into the configuration file,
azure.keyvault.enabled=true
azure.keyvault.uri=https://blog-core-keyvault.vault.azure.cn/
azure.keyvault.client-id=你的应用id
azure.keyvault.client-key=你的应用密钥
azure.keyvault.tenant-id=你的tenantid
azure.keyvault.authority-host=https://login.chinacloudapi.cn
Note that the last configuration is very important, you need to specify the host address, because the default is Azure.com, if you are Azure.com, you can not specify.
Step 2 - Get the value of the Key Vault anywhere
The method of use here is exactly the same as that in ordinary yml, configure variables, and annotate them with @value:
@SpringBootApplication
public class KeyvaultApplication implements CommandLineRunner {
@Value("${MSSQL-USER-NAME}")
private String mySecretProperty;
public static void main(String[] args) {
SpringApplication.run(KeyvaultApplication.class, args);
}
@Override
public void run(String... args) {
System.out.println("property your-property-name value is: " + mySecretProperty);
}
}
Well, in the Java application, the connection to Azure Key Vault is finished, you can try to get in touch.
Summarize
This article uses ASP.NET Core and Java as examples to explain how to connect the Key Vault configuration in Azure. The overall process is simple and convenient, and the documentation is particularly clear. Once again, cheers for the Microsoft Docs documentation.
- Source Link:
https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/spring/azure-spring-boot-starter-keyvault-secrets
https://devblogs.microsoft.com/dotnet/category/net-core/?WT.mc_id=DOP-MVP-5003704
Microsoft Most Valuable Professional (MVP)
The Microsoft Most Valuable Professional is a global award given to third-party technology professionals by Microsoft Corporation. For 28 years, technology community leaders around the world have received this award for sharing their expertise and experience in technology communities both online and offline.
MVPs are a carefully selected team of experts who represent the most skilled and intelligent minds, passionate and helpful experts who are deeply invested in the community. MVP is committed to helping others and maximizing the use of Microsoft technologies by Microsoft technical community users by speaking, forum Q&A, creating websites, writing blogs, sharing videos, open source projects, organizing conferences, etc.
For more details, please visit the official website:
https://mvp.microsoft.com/zh-cn
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。