我将.jks文件放在spring boot app的资源目录中,现在我需要使用system属性配置密钥存储。尝试了多种方法,例如使用System.setProperty("javax.net.ssl.keyStore", "abc.jks");
System.setProperty("javax.net.ssl.keyStore", "classpath:abc.jks");
设置属性,除了在文件系统System.setProperty("javax.net.ssl.keyStore", "D:/../abc.jks");
中提供完整路径外,其他方法都无济于事。如何配置系统属性值,使其起作用。我不希望为嵌入式tomcat启用它。只想将其设置为jvm。
最佳答案
您需要这样的东西:
application.properties
server.port: 8443
server.ssl.key-store: classpath:${KEYSTORE:keystore.p12}
server.ssl.key-store-password: password
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
如果没有,它将寻找一个系统属性KEYSTORE,它将默认为keystore.p12,因此应用程序可以像这样运行:
java -jar target/spring-boot-https-1.0.jar
要么
java -DKEYSTORE=anotherKeystore.p12 -jar target/spring-boot-https-1.0.jar
如果keystore.p12在resources目录中,这就是您需要做的所有工作
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
@LocalServerPort
private int port;
private RestTemplate template;
@Before
public void setUp() throws Exception {
createTemplateFromKeyStore("keystore.p12");
}
@Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity("https://localhost:" + port + "/", String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
private void createTemplateFromKeyStore(String keyStoreName) {
try {
InputStream keyStoreInputStream = getClass().getResourceAsStream(keyStoreName);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(keyStoreInputStream, null);
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
.loadTrustMaterial(keyStore, new TrustAllStrategy()).build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
template = new RestTemplate(requestFactory);
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
}
见example project
话虽如此,您最好使用spring profiles并拥有多个application.properties
application-dev.properties
application-prod.properties
它们具有不同的值,并可以从命令行进行控制
java -Dspring.profiles.active=dev -jar target/spring-boot-https-1.0.jar
关于java - 使用Spring Boot资源目录内的系统属性设置 keystore 文件位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49108472/