Spring Boot配置ssl证书启用HTTPS协议
- 2019 年 10 月 8 日
- 筆記
一 、点睛
SSL是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密。SSL协议位于TCP/IP协议和各种应用层协议之间,为数据通信提供安全支持。
SSL协议分为两层:SSL记录协议,它建立在可靠的传输协议(如TCP)之上,为高层协议提供数据封装、压缩、加密等基本功能的支持。SSL握手协议,它建立在SSL记录协议之上。用于在实际数据传输开始前,通信双方进行身份认证、协商加密算法、交换加密密钥等。
基于B/S的Web应用中,是通过HTTPS来实现SSL的。HTTPS是以安全为目标的HTTP通信,简单讲是HTTP的安全版,即在HTTP下加入SSL层,HTTPS的安全基础是SSL。 !
二、用JDK中keytool生成自带签名证书
使用SSL首先需要一个证书,这个证书既可以是自签名的,也可以是从SSL证书授权中心获得的。本案例演示自签名证书的生成。
JDK或JRE中的keytool工具是一个证书管理工具,可以用来生成自签名证书。

在命令行输入以下内容

此时生成一个.keystore文件,这就是我们要用的证书文件
三、将.keystore证书文件(复制到项目的application.properties同级目录)

四、修改Spring Boot的application.properties

五、修改启动类,让http重定向到https
XXXApplication.java
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 WebchatApplication {
public static void main(String[] args) { SpringApplication.run(WebchatApplication.class, args); }
/** * http重定向到https * @return */ @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(8080); connector.setSecure(false); //监听到http的端口号后转向到的https的端口号 connector.setRedirectPort(8044); return connector; } }

启动成功后,打开Chrome浏览器,输入SpringBoot的URL映射,可以看到弹出了证书不安全的提示,单击【高级】–>【继续前往】即可正常打开网址链接了。
注意:由于JDK生成的自签名证书没有经过CA机构认证,所以会提示不安全。
