生成自签名证书
# keytool是安装JDK自带的工具,keysize大小一般取2048就够了,太大影响解析速度。
# validity有效期我直接整了个100年
# 最后得到的文件就是xx.p12,别名取<alias>
# 命令执行过程中会提示要密钥密码,这个要记住,后面SpringBoot要用到
keytool -genkey -alias <alias> -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore ./xx.p12 -validity 36500
项目部署
证书复制
首先复制p12文件至项目根目录
##配置类
目的是让所有的http请求转向https请求
package com.CmJava.configuration;
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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SSLConfig {
// 我在application.yaml里面写了http: port: 80
@Value("${http.port}")
Integer httpPort;
//正常启用的https端口 如443
@Value("${server.port}")
Integer httpsPort;
@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() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(80);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}
评论区