spring boot项目配置ssl证书
spring boot项目配置ssl证书
1. 生成所需的证书
本教程参考了其他教程因此, 证书类型统一为jks,先将现在通用的pfx证书转换为jks
cd /d %JAVA_HOME%/bin
keytool -importkeystore -srckeystore *****.pfx -destkeystore ****.jks -srcstoretype PKCS12 -deststoretype JKS
# 67f764daed912a95b603b8128b03d043
#Warning:
#JKS 密钥库使用专用格式。建议使用 "keytool -importkeystore -srckeystore ****.jks -destkeystore ****.jks -deststoretype pkcs12" 迁移到行业标准格式 PKCS12。
2. 配置yaml
#https加密端口号 443
server.port=443
#SSL证书路径 一定要加上classpath:
#改成自己需要的证书名
server.ssl.key-store=classpath:*****.jks
#SSL证书密码
server.ssl.key-store-password=12345678
#证书类型
server.ssl.key-store-type=JKS
#证书别名
server.ssl.key-alias=1
server.ssl.enabled=true
3. 更改启动类
package com.barry.login;
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 DiyApplication {
public static void main(String[] args) {
SpringApplication.run(DiyApplication.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(443);//可调整到自己所需要的端口号
return connector;
}
}
4. pom配置
编译之后会进行压缩等算法, 会破坏密钥, 需要设置
配置完之后, 先clean
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>*.jks</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>*.jks</include>
</includes>
</resource>
</resources>
</build>
5. 参考
证书配置
https://blog.csdn.net/sinat_40399893/article/details/79860942
maven配置
https://blog.csdn.net/kevin_mails/article/details/84590449
filtering已经是false了,没毛病,但是还是不行,这是为啥?(certificate目录下是.jks文件),看到个别有的文章说配置了filtering=false 没效,估计跟我这配置应该是差不多的,参考下面的方法:
后来调整了一下配置: