Embedded Tomcat SSL Config
2021-03-02 本文已影响0人
liuliuzo
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.IOException;
@Configuration
public class SslConfigBean {
@Value("${https.port}")
private Integer port;
@Value("${https.ssl.key-store-password}")
private String key_store_password;
@Value("${https.ssl.key-password}")
private String key_password;
@Value("${https.ssl.key-store}")
private String cerpath;
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}
/**
* verify client
**/
@Bean
public Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource(cerpath).getFile();
File truststore = new ClassPathResource(cerpath).getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(port);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass(key_store_password);
protocol.setKeyPass(key_password);
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass(key_password);
protocol.setClientAuth("false");
return connector;
} catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore" + "] or truststore: [" + "keystore" + "]", ex);
}
}
}