Spring Boot中启动HtoTTPS
如果你使用Spring Boot,并且想在内嵌mcat中添加HTTPS,需要如下步骤
- 要有一个证书,买的或者自己生成的
- 在Spring Boot中启动HTTPS
- 将HTTP重定向到HTTPS
获取SSL证书
有两种方式
- 自己通过keytool生成
- 通过证书授权机构购买
这里作为演示,采用keytool生成
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
2、springboot中使用https
修改配置文件
server.port=8443 #security.headers.hsts=all server.ssl.key-store=keystore.p12 server.ssl.key-store-password=tomcat erver.ssl.keyStoreType=PKCS12 server.ssl.keyAlias:tomcat
3设置重定向,修改启动类
package com.example; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint constraint = new SecurityConstraint(); constraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); constraint.addCollection(collection); context.addConstraint(constraint); } }; tomcat.addAdditionalTomcatConnectors(httpConnector()); return tomcat; } @Bean public Connector httpConnector() { System.out.println("hello redict"); Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); //Connector监听的http的端口号 connector.setPort(8080); connector.setSecure(false); //监听到http的端口号后转向到的https的端口号 connector.setRedirectPort(8443); return connector; } }
4、同时开启htst表头