spring boot 集成ssl
https 默认配置端口443,http 80
SSL 获取方式
阿里云,腾讯云申请免费单域名证书,解压后会出现两个文件,一个是密码,一个SSL证书
jdk 对源证书进行加密处理
密码最好和源密码一样
操作步骤
打开cmd命令,切到jdk安装的bin包下,如下图,输入命令后会提示输入三次密码,前两次自定义密码,最后一次源密码,也是下载阿里证书文件里面的密码
keytool -importkeystore -srckeystore 2832703_gshp.top.pfx(阿里证书源文件) -destkeystore gshp.jks(生成的文件) -srcstoretype PKCS12(加密方式) -deststoretype JKS
image.png
spring boot 集成SSL
application.yml 添加配置
注意不要写错哦,博主配置引用错误,报错WebServerException: Could not load key store 'null'
应用配置
image
spring boot 配置监听,http访问自动跳转https
package com.gshp.config;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.api.WebResourceCollection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 采用Undertow作为服务器,支持https服务配置和HTTP2.0协议
*
*/
@Configurationpublic
class WebServerConfiguration {
/**
* http服务接口
*/
@Value("${gshp.server.http.port}")
private Integer httpPort;
@Value("${server.port}")
private Integer httpsPort;
@Bean
public ServletWebServerFactory undertowFactory(){
UndertowServletWebServerFactory undertowFactory = new UndertowServletWebServerFactory();
undertowFactory.addBuilderCustomizers((Undertow.Builder builder) -> {
builder.addHttpListener(httpPort, "0.0.0.0");
// 开启HTTP2
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
});
undertowFactory.addDeploymentInfoCustomizers(deploymentInfo -> {
// 开启HTTP自动跳转至HTTPS
deploymentInfo.addSecurityConstraint(
new SecurityConstraint().addWebResourceCollection(
new WebResourceCollection().addUrlPattern("/*"))
.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT))
.setConfidentialPortManager(exchange -> httpsPort);
});
return undertowFactory;
}
}
——有遇到什么问题,欢迎评论区讨论
image.png