如今,企业级应用程序的常见场景是同时支持HTTP和HTTPS两种协议,这篇文章考虑如何让Spring Boot应用程序同时支持HTTP和HTTPS两种协议。
准备
为了使用HTTPS连接器,需要生成一份Certificate keystore,用于加密和机密浏览器的SSL沟通。
如果你使用Unix或者Mac OS,可以通过下列命令:keytool -genkey -alias tomcat -keyalg RSA
,在生成过程中可能需要你填入一些自己的信息,例如我的机器上反馈如下:
可以看出,执行完上述命令后在home目录下多了一个新的.keystore文件。
实战首先在resources目录下新建一个配置文件tomcat.https.properties,用于存放HTTPS的配置信息;
custom.tomcat.https.port=8443 custom.tomcat.https.secure=true custom.tomcat.https.scheme=https custom.tomcat.https.ssl=true custom.tomcat.https.keystore=${user.home}/.keystore custom.tomcat.https.keystore-password=changeit
然后在WebConfiguration类中创建一个静态类TomcatSslConnectorProperties;
@ConfigurationProperties(prefix = "custom.tomcat.https") public static class TomcatSslConnectorProperties { private Integer port; private Boolean ssl = true; private Boolean secure = true; private String scheme = "https"; private File keystore; private String keystorePassword; //这里为了节省空间,省略了getters和setters,读者在实践的时候要加上 public void configureConnector(Connector connector) { if (port != null) { connector.setPort(port); } if (secure != null) { connector.setSecure(secure); } if (scheme != null) { connector.setScheme(scheme); } if (ssl != null) { connector.setProperty("SSLEnabled", ssl.toString()); } if (keystore != null && keystore.exists()) { connector.setProperty("keystoreFile", keystore.getAbsolutePath()); connector.setProperty("keystorePassword", keystorePassword); } } }
通过注解加载tomcat.https.properties配置文件,并与TomcatSslConnectorProperties绑定,用注解修饰WebConfiguration类;
@Configuration @PropertySource("classpath:/tomcat.https.properties") @EnableConfigurationProperties(WebConfiguration.TomcatSslConnectorProperties.class) public class WebConfiguration extends WebMvcConfigurerAdapter {...}
在WebConfiguration类中创建EmbeddedServletContainerFactory类型的Srping bean,并用它添加之前创建的HTTPS连接器。
@Bean public EmbeddedServletContainerFactory servletContainer(TomcatSslConnectorProperties properties) { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); tomcat.addAdditionalTomcatConnectors(createSslConnector(properties)); return tomcat; } private Connector createSslConnector(TomcatSslConnectorProperties properties) { Connector connector = new Connector(); properties.configureConnector(connector); return connector; }
通过mvn spring-boot:run
启动应用程序;在浏览器中访问URLhttps://localhost:8443/internal/tomcat.https.properties