Akshay Sonvane
Akshay Sonvane

Reputation: 51

How can I programmatically supply the keystore file with Spring Boot and Tomcat?

I know that we can configure the keystore's file location using

server.ssl.key-store=file:/path/to/file.p12

Due to security concerns, we would like to get rid of the P12 file on disk and fetch it directly from the cloud providers vault. Since the keystore's password can be configured, I can set it using https://stackoverflow.com/a/44971126/4460877

Is there a similar approach for configuring the keystore file rather than the file location by fetching it from the cloud provider?

Upvotes: 3

Views: 3116

Answers (1)

Akshay Sonvane
Akshay Sonvane

Reputation: 51

I was able to set the keystore file programmatically using the WebServerFactoryCustomizer as follows

    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatSslStoreCustomizer() {
        // Supply key store password
        String keyStorePassword;
        // Supply key store file as a stream
        InputStream keyStoreFile;
        KeyStore keyStore;

        try (InputStream is = keyStoreFile) {
            keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
            keyStore.load(is, keyStorePassword.toCharArray());
        }
        catch (Exception e) {
            throw new RuntimeException("Cannot load keystore file; cause: " + e.getMessage(), e);
        }

        return tomcat -> tomcat.setSslStoreProvider(new SslStoreProvider() {
            @Override
            public KeyStore getKeyStore() {
                return keyStore;
            }

            @Override
            public KeyStore getTrustStore() {
                return null;
            }
        });
    }

Upvotes: 2

Related Questions