一、生成SSL证书:
打开DOM,输入keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650,完成以下配置:
二 、配置SSL证书:
1、复制SSL证书到项目根目录。
2、再配置properties:
#设置SSL证书配置HTTPS ————————————————————————————————————#
#证书名字
server.ssl.key-store=keystore.p12
#证书密码
server.ssl.key-store-password=123456
#证书编码
server.ssl.key-store-type=PKCS12
#生成证书服务器
server.ssl.key-alias=tomcat
三、配置Spring Boot启动器实现HTTPS与HTTP自动转换:
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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class IndexApplication {
public static void main(String[] args) {
SpringApplication.run(IndexApplication.class, args);
}
@Bean
public Connector connector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8001); //http监控端口
connector.setSecure(false);
connector.setRedirectPort(8000); //https监控端口
return connector;
}
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
@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(connector);
return tomcat;
}
}
四、测试:
浏览器输入http://localhost:8001/index会自动跳转https://localhost:8000/index