若是你使用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 設置完畢