SSL(Secure Sockets Layer 安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密,SSL协议位于TCP/IP协议与各种应用层协议之间,为数据通信提供安全支持。SSL协议分为两层,SSL记录协议建立在TCP之上,为高层协议提供数据封装、压缩、加密等基本功能支持。SSL握手协议建立在SSL记录协议之上,用户实际数据传输开始前进行身份验证、协商加密算法、交换加密秘钥。
生成证书,可以使自签名或者从SSL证书授权中心获得的
JDK中keytool是一个证书管理工具,可以生成自签名证书。本人这里用的系统是deepin,然后生成命令如下(找不到keytoo命令的先去配置java环境)我指定的名字叫tomcat.keystore 别名叫tomcat,密码自己设置,我这里用的tomcat,最后那个直接按得回车。
keytool -genkey -alias tomcat -keyalg RSA -keystore d:/test/tomcat.keystore
2.SpringBoot配置SSL
把tomcat.keystore拷贝到SpringBoot工程的 src/resources目录下。配置application.properties
### https configuration server.port=7443 server.ssl.key-store=d:/test/tomcat.keystore server.ssl.key-alias=tomcat server.ssl.enabled=true server.ssl.key-store-password=123456 server.ssl.key-store-type=JKS
此刻启动项目,跳转到 https://localhost:8443 。在运行主类里面,加入如下代码
package com.wx.weixin; 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; import org.apache.catalina.Context; @SpringBootApplication public class WeixinApplication { public static void main(String[] args) { SpringApplication.run(WeixinApplication.class, args); } @Bean public Connector connector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8082); connector.setSecure(false); connector.setRedirectPort(7443); 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; } }