SpringBoot配置HTTPS,并实现HTTP访问自动转HTTPS访问
# 生成服务器端证书
keytool -genkey -alias tomcat -keyalg RSA -keystore ./server.keystore
1
2
3
2
3
# 生成客户端证书
keytool -keystore server.keystore -export -alias tomcat -file ./server.cer
1
2
3
2
3
# 配置 springBoot
server:
port: 8085
ssl:
key-store-password: 123456
key-alias: tomcat
key-store: classpath:server.keystore
enabled: true
key-store-type: JKS
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 配置 Config
@Configuration
@Profile("dev")
public class SSLConfig {
@Value("${server.port}")
private int sslPort;//https的端口
/**
* @Description: 重定向请求到端口,需要端口转发时使用
* @Author: fanfan
* @Date: 2020-05-19 15:47
*/
@Bean
public Connector connector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(sslPort);
return connector;
}
/**
* @Description: 重定向到HTTPS
* @Author: fanfan
* @Date: 2020-05-19 15:47
*/
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory(){
TomcatServletWebServerFactory factory = 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);
}
};
// factory.addAdditionalTomcatConnectors(connector());
return factory;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# tip
// 查看端口
netstat -ano
// 查看进程
tasklist|findstr (查看到的进程号)
# simple
C:\Users\Administrator>tasklist|findstr 3664
vmware-hostd.exe 3664 Services 0 5,040 K
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11