介绍:在实际项目开发过程中,我们用到的http协议是不安全的,大家都知道http传输协议是裸漏的,明文传输的,极易被黑客拦截,因此我们要用到 https。https 是以安全为目标的 http 通道,而 https 的安全基础是 SSL。
下面我们老样子废话少说,开始实战:
1.准备证书,有两种方式大家看仔细喽
1)配置环境jdk环境量之后在cmd下输入,根据提示生成证书,未配置环境变量在jdk/bin目录下输入,生成证书
keytool -genkeypair -alias tomcat -keyalg RSA -keystore E:\tomcat.key
//其中-alias是证书的别名,RSA是加密算法,-keystore后是输出证书的路径所在
2)到阿里云下载证书页面下载证书,在我们项目开发中一般使用购买的证书,以阿里云为例
2.复制证书至spring boot项目的根目录
3.在spring boot 配置文件中添加ssl属性
# 证书路径
ssl.key-store: tomcat.key
ssl.key-store-type: JKS
ssl.key-alias: tomcat
# 配置密码,就是在生成证书的时候输入的密码
ssl.key-store-password: 123456
以上部分已经可以满足https通信协议,但如需同时启动https+http两个端口请看下面
4.在启动类中配置同时启动https+http端口并配置重定向
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");//confidential
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
5.访问一下,看看效果
浏览器输入http://localhost:8080/index.html跳转到http://localhost:8443/index.html
或直接输入http://localhost:8443/index.html