Specifying trust store information in spring boot application.properties

user4408912 picture user4408912 · Dec 31, 2014 · Viewed 160.3k times · Source

I am using springBootVersion 1.2.0.RELEASE. I'm trying to have my keystore and truststore configured through application.properties.

When I add the following settings, I can get the keystore to work, but not the truststore.

server.ssl.key-store=classpath:foo.jks
server.ssl.key-store-password=password
server.ssl.key-password=password
server.ssl.trust-store=classpath:foo.jks
server.ssl.trust-store-password=password

However, if I add the truststore through gradle:

bootRun {
    jvmArgs = [ "-Djavax.net.ssl.trustStore=c://foo.jks", "-Djavax.net.ssl.trustStorePassword=password"]
}

it works just fine.

Has anyone used the application.properties for trust stores?

Answer

Sasha Shpota picture Sasha Shpota · Apr 5, 2017

In case if you need to make a REST call you can use the next way.

This will work for outgoing calls through RestTemplate.

Declare the RestTemplate bean like this.

@Configuration
public class SslConfiguration {
    @Value("${http.client.ssl.trust-store}")
    private Resource keyStore;
    @Value("${http.client.ssl.trust-store-password}")
    private String keyStorePassword;

    @Bean
    RestTemplate restTemplate() throws Exception {
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(
                        keyStore.getURL(),
                        keyStorePassword.toCharArray()
                ).build();
        SSLConnectionSocketFactory socketFactory = 
                new SSLConnectionSocketFactory(sslContext);
        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory).build();
        HttpComponentsClientHttpRequestFactory factory = 
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }
}

Where http.client.ssl.trust-store and http.client.ssl.trust-store-password points to truststore in JKS format and the password for the specified truststore.

This will override the RestTemplate bean provided with Spring Boot and make it use the trust store you need.