前言
因为小程序所请求的后台必须为https://所以SSL证书配置不可获缺,这里不能使用tomcat自制证书必须去购买,各大云服务器都有免费的证书可以申请
一、搞个证书
专家安装84元????没错,本篇文章价值84元,就算我不是专家,那也值80元
下载之后解压到一个文件夹里面包含2个文件TXT文件中包含的就是密码
二、打包为jks文件
为啥要打包为jks文件?
因为Tomcat 目前只能操作 JKS、PKCS11、PKCS12 格式的密钥存储库
在CMD中进入jdk的bin目录输入转换命令
keytool
-importkeystore
-srckeystore G
:\https\
2247331_abstergo
.xin
.pfx
-destkeystore myWeb
.jks
-srcstoretype PKCS12
-deststoretype JKS
G:\https\2247331_abstergo.xin.pfx就是第一步中解压的地址 这里要输入3个密码来字解压文件中的TXT文件内的密码 不要看他说输入新口令,信了就两个小时后见。实际上必须输入那一个密码,要输入三次一样,输入三次一样,输入三次一样!!!,不然会一直报端口被占用这个错,不要问我为什么,我找了2个小时,找了所有的帖子都没有解决的办法,还好我机智…记住别名,配置文件中需要填写,记不住也没关系,反正可以查 回车之后会多出这样一个文件,复制到resource目录下与application.properties同级检查是否建立成功(也可以查看别名) keytool -list -v -keystore myWeb.jks 检测jks是否有误
三、配置application.properties
jks文件要和application.properties同级 #https加密端口号
443
server
.port
=443
#SSL证书路径 一定要加上classpath
:
server
.ssl
.key
-store
=classpath
:myWeb
.jks
#SSL证书密码
server
.ssl
.key
-store
-password
=你的密码
#证书类型
server
.ssl
.key
-store
-type
=JKS
#证书别名
server
.ssl
.key
-alias
=alias
没有classpath:也会报端口被占用的错,人类的本质是…
四、http自动跳转为https
package com
.example
.demo
;
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 DemoApplication {
public static void main(String
[] args
) {
SpringApplication
.run(DemoApplication
.class, args
);
}
@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
.setPort(1024);
connector
.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector
.setRedirectPort(443);
return connector
;
}
}