若是你使用Spring Boot,而且想在内嵌tomcat中添加HTTPS,须要以下步骤spring
有两种方式apache
这里做为演示,采用keytool生成编程
输入下面的命令,根据提示输入信息tomcat
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: What is the name of your organizational unit? [Unknown]: What is the name of your organization? [Unknown]: What is the name of your City or Locality? [Unknown]: What is the name of your State or Province? [Unknown]: What is the two-letter country code for this unit? [Unknown]: Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct? [no]: yes
会生成一个PKCS12格式的叫作keystore.p12的证书,以后启动Spring Boot时会引用这个证书服务器
默认状况下Spring Boot内嵌的Tomcat服务器会在8080端口启动HTTP服务,Spring Boot容许在application.properties中配置HTTP或HTTPS,可是不可同时配置,若是两个都启动,至少有一个要以编程的方式配置,Spring Boot官方文档建议在application.properties中配置HTTPS,由于HTTPS比HTTP更复杂一些,能够参考spring-boot-sample-tomcat-multi-connectors的实例app
在application.properties中配置HTTPSide
server.port: 8443 server.ssl.key-store: classpath:keystore.p12 server.ssl.key-store-password: mypassword server.ssl.keyStoreType: PKCS12 server.ssl.keyAlias: tomcat
这就够了spring-boot
让咱们的应用支持HTTP是个好想法,可是须要重定向到HTTPS,上面说了不能同时在application.properties中同时配置两个connector,因此要以编程的方式配置HTTP connector,而后重定向到HTTPS connectorpost
这须要在配置类中配置一个TomcatEmbeddedServletContainerFactory bean,代码以下this
@Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(initiateHttpConnector()); return tomcat; } private Connector initiateHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; }
SSL 设置完毕