我不是 Java/Spring Boot 开发人员,但我想构建一个简单的 Spring boot 应用程序,该应用程序可以从 Key Vault 读取配置并连接到 SQL。
我对其中每一个都有两个单独的解决方案
Key Vault 解决方案是从 Azure Key Vault 读取机密
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
@SpringBootApplication
@RestController
public class KeyvaultApplication {
public static void main(String[] args) {
SpringApplication.run(KeyvaultApplication.class, args);
}
@GetMapping("get")
public String get() {
return connectionString;
}
@Value("${connectionString}")
private String connectionString;
public void run(String... varl) throws Exception {
System.out.println(String.format("\nConnection String stored in Azure Key Vault:\n%s\n",connectionString));
}
}
应用程序属性
azure.keyvault.client-id=xxxx
azure.keyvault.client-key=xxxx
azure.keyvault.enabled=true
azure.keyvault.tenant-id=xxxxx
azure.keyvault.uri=https://xxxxx-keyvault85.vault.azure.net/
====================================================== =====================
以及将数据插入 Azure SQL 数据库的 SQL 解决方案
应用程序属性
logging.level.org.springframework.jdbc.core=DEBUG
spring.datasource.url=jdbc:sqlserver://xxxx-sql.database.windows.net:1433;database=demo;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
spring.datasource.username=spring@databasename
spring.datasource.password=Password
spring.datasource.initialization-mode=never
TodoController.java
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/")
public class TodoController {
private final TodoRepository todoRepository;
public TodoController(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
@PostMapping("/")
@ResponseStatus(HttpStatus.CREATED)
public Todo createTodo(@RequestBody Todo todo) {
return todoRepository.save(todo);
}
@GetMapping("/")
public Iterable<Todo> getTodos() {
return todoRepository.findAll();
}
}
TodoRepository.java
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface TodoRepository extends CrudRepository<Todo, Long> {
}
Todo.java
package com.example.demo;
import org.springframework.data.annotation.Id;
public class Todo {
public Todo() {
}
public Todo(String description, String details, boolean done) {
this.description = description;
this.details = details;
this.done = done;
}
@Id
private Long id;
private String description;
private String details;
private boolean done;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
这两个解决方案都是独立工作的,但我想组合这些解决方案,以便我可以从 Azure Key Vault 读取 SQL 配置并与 Azure SQL 数据库连接。我如何实现这一目标?
您可以参考此文档:教程:在 Spring Boot 应用程序中从 Azure Key Vault 读取机密:
Spring Boot 应用程序外部化敏感信息,例如用户名和密码。外部化敏感信息可以实现更好的可维护性、可测试性和安全性。在代码之外存储秘密比对信息进行硬编码或在构建时内联要好。
本教程介绍如何创建从 Azure Key Vault 读取值的 Spring Boot 应用程序,然后将该应用程序部署到 Azure 应用服务和 Azure Spring Cloud。
将 Key Vault 集成添加到应用程序的摘要:
按照以下步骤将必要的配置添加到application.properties 文件中。
azure.keyvault.client-id=685on005-ns8q-4o04-8s16-n7os38o2ro5n
azure.keyvault.client-key=4bt.lCKJKlbYLn_3XF~wWtUwyHU0jKggu2
azure.keyvault.enabled=true
azure.keyvault.tenant-id=72s988os-86s1-41ns-91no-2q7pq011qo47
azure.keyvault.uri=https://contosokv.vault.azure.net/
可用属性的完整列表记录在
属性参考.
import org.springframework.beans.factory.annotation.Value;
@Value("${connectionString}")
private String connectionString;
Key Vault 集成提供了一个 Spring PropertySource
,它由 Key Vault 的值。一些更多的实现细节可以在参考文档。
mvn clean package spring-boot:run
。
Bash
$ curl http://localhost:8080/get
输出将显示
jdbc:sqlserver://SERVER.database.windows.net:1433;database=DATABASE
代替
defaultValue
。
mvn spring-boot:run
运行的进程。你可以 输入 Ctrl-C 或者您可以使用
jps
命令来获取 pid
Launcher
处理并杀死它。
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-keyvault-secrets-spring-boot-starter</artifactId>
<version>2.1.7</version>
</dependency>
只需要3个参数。YAML 文件
azure:
keyvault:
client-id: xxxxxxx
client-key: xxxxxxyyyyy
enabled: true
uri: https://xxx.vault.azure.net/
然后是Config类
@Configuration
public class AzureConfig {
@Value("${azure.keyvault.client-id}")
private String clientId;
@Value("${azure.keyvault.client-key}")
private String clientSecret;
@Bean
public KeyVaultClient keyVaultClient() {
ServiceClientCredentials credentials = new AzureKeyVaultCredential(clientId, clientSecret);
return new KeyVaultClient(credentials);
}
}
然后在服务类中自动装配keyVaultClient
来设置或获取
SetSecretRequest secretRequest = new Builder(keyVaultUrl, key, value).build();
keyVaultClient.setSecret(secretRequest);
keyVaultUrl
是密钥保管库主机 URL,如
https://xxx.vault.azure.net/
Configuration
类,它可以为我们初始化
SecretClient
对象。
@Configuration
public class AzureSecretClientConfiguration {
@Bean
public SecretClient createSecretClient() {
return new SecretClientBuilder()
.vaultUrl("https://app-kv.vault.azure.net/")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
}
}
下一步将使用此配置对象基于 key-vault
secret-key-name
获取秘密
A sql-server configuration
现在可以使用
AzureSecretClientConfiguration
对象从 azure 密钥保管库获取机密。我在
applicaiton.properties
中定义了以下变量。请注意每个变量如何引用 azure key-vault 中的键名称。
# SQL Server Properties
spring.datasource.url.azure.key=sql-server-metastore-db-uri
spring.datasource.username.azure.key=sql-server-metastore-db-username
spring.datasource.password.azure.key=sql-server-metastore-db-password
来自 Azure Key-Vault 的条目 -
现在 Sql Server Config
类可以使用之前创建的
AzureSecretClientConfiguration
SecretClient 来获取并创建自己的配置对象。请参考下面的
getSecret()
功能 -
@Configuration
public class SqlServerKeyVaultConfig {
@Autowired
AzureSecretClientConfiguration azureSecretClientConfiguration;
@Value("${spring.datasource.url.azure.key}")
private String sqlServerDbUriSecretName;
@Value("${spring.datasource.username.azure.key}")
private String sqlServerUsernameSecretName;
@Value("${spring.datasource.password.azure.key}")
private String sqlServerPasswordSecretName;
@Bean
public String sqlServerDbUrl() {
System.out.println("Data-source url " + sqlServerDbUriSecretName);
return getSecret(sqlServerDbUriSecretName);
}
@Bean
public String sqlServerUsername() {
return getSecret(sqlServerUsernameSecretName);
}
@Bean
public String sqlServerPassword() {
return getSecret(sqlServerPasswordSecretName);
}
private String getSecret(String secretName) {
return azureSecretClientConfiguration.createSecretClient().getSecret(secretName).getValue();
}
}