Reputation: 165
I want to implement SSL in spring boot application wherein, i also want to encrypt (For testing purpose i am encoding it by base 64) the password to the keystore, which i am passing as JVM arguments to the spring boot application.
This password to keystore will be later used in following way to decrypt (for now base 64 decode) and form the EmbeddedServletContainerFactory on the fly.
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory();
tomcatFactory.setSsl(createSsl());
tomcatFactory.setPort(sslConfig.getHttpsPort());
return tomcatFactory;
}
private Ssl createSsl() {
Ssl ssl = new Ssl();
try {
ssl.setKeyStore("/path/to/keystore.pkcs12");
ssl.setKeyStorePassword(new String(Base64.getDecoder().decode(sslConfig.getKeyPassword())));
ssl.setKeyAlias(sslConfig.getKeyAlias());
} catch (Exception e) {
logger.error(e.getMessage());
}
return ssl;
}
JVM arguments :
-Dtls.keyAlias=tomcat
-Dtls.key-store-password=cGFzc3dvcmQ=
POJO to store the alias and password getting from JVM arguments :
@Component
public class SSLConfig {
@Value("#{systemProperties['tls.keyAlias']}")
public String keyAlias;
@Value("#{systemProperties['tls.key-store-password']}")
private String keyPassword;
....getters n setters
}
The above configuration is working absolutely fine.
Now, I want to achieve this based on some flag which will be passed through JVM arguments say "isSSLEnabled", on setting which the control should flow through above logic, otherwise it should work in default way.
Can someone please guide on this ?
Upvotes: 1
Views: 417
Reputation: 47905
You can use Spring Boot's ConditionalOnProperty annotation to make your servletContainer()
bean conditional on the value of an isSSLEnabled
property/JVM argument.
For example:
@Bean
@ConditionalOnProperty(name = "isSSLEnabled", havingValue = "true")
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory();
tomcatFactory.setSsl(createSsl());
tomcatFactory.setPort(sslConfig.getHttpsPort());
return tomcatFactory;
}
private Ssl createSsl() {
Ssl ssl = new Ssl();
try {
ssl.setKeyStore("/path/to/keystore.pkcs12");
ssl.setKeyStorePassword(new String(Base64.getDecoder().decode(sslConfig.getKeyPassword())));
ssl.setKeyAlias(sslConfig.getKeyAlias());
} catch (Exception e) {
logger.error(e.getMessage());
}
return ssl;
}
Upvotes: 5