0:目标:http://localhost访问直接跳转到https://localhost的访问
2.组件相关逻辑参考:
https://cloud.tencent.com/document/product/400/4143
3.使用jdk自带的 keytools 创建证书
https://www.jianshu.com/p/8d4aba3b972d
4.核心代码
https://www.iteye.com/blog/wallimn-2425837
一、启动程序
Java代码
@SpringBootApplication
public class AssetApplication {
//如果没有使用默认值80
@Value("${http.port:80}")
Integer httpPort;
//正常启用的https端口 如443
@Value("${server.port}")
Integer httpsPort;
// springboot2 写法
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat =new TomcatServletWebServerFactory() {
@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("启用http转https协议,http端口:"+this.httpPort+",https端口:"+this.httpsPort);
Connector connector =new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(httpPort);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(httpsPort);
return connector;
}}
二、配置文件
1.使用http协议时的配置
server.port=80
2.使用https及http协议时的配置
server.port=443 【默认springboot的默认启动端口是8080,现在的目标是让默认端口为https端口,即443端口,那么就要配置设置成443,并且注意这个路径 是 server.port 不是 server.tomcat.port】
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=your-password
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=your-cert-alias
condition.http2https=true
http.port=80
3.Spring-Security 启用安全通道(https)的一步步实现
发现Spring Security默认是内置个两组对应的映射端口(80->443,8080->8443)。到这里上面出错就好理解了,我测试用的tomcat,设置的http请求监听端口是8898,根本就找不到对应的https端口。
https://www.cnblogs.com/MrSi/p/8004419.html