说明
由于SpringBoot2新版本的发布,有些新特性,在此就不一一列举。由于这些变化,在实际开发中带来了一些问题,在此记录下,避免其他人再掉坑。主要步骤包括:
- 生成证书
- 修改配置文件
- 增加配置类
- 实现HTTP转HTTPS
生成证书
- 获取证书可通过购买,或者本机生成,以下演示本机生成
- 通过
keytool -genkey alias selfsigned_sslserver
生成的.keystore
已经过时了,不推荐 - 在正确配置完JDK环境变量的前提下,在任意目录,执行命令
keytool -genkey -alias selfsigned_sslserver-storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
- 按提示填好相关信息……
- 在当前目录下会生成一个
keystore.p12
文件,即证书文件
修改配置文件
- 将证书文件放入
resources
目录下 - 修改application.properties文件
server.port=443
server.ssl.key-alias=selfsigned_sslserver
server.ssl.key-store-password=your_passwd
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-type=PKCS12
增加配置类,包括实现HTTP端口转换HTTPS(可选重定向配置)
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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SSLConfig {
@Bean
public ServletWebServerFactory servletContainer() {
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(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector(
TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}