使用Spring boot

时间:2018-03-05 10:37:31

标签: java spring ssl spring-boot

我将.jks文件放在spring boot app的资源目录中,现在我需要使用系统属性配置密钥存储区。尝试了各种方法,例如使用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。

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

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在资源目录中,那么你需要做的就是测试

@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