项目代码
package com.hst.ces.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.autoconfigure.condition.ConditionalOnProperty;
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;
/**
* @author SunYang
* @version 1.0
* @description: 容器https配置
* @date 2021/01/19 20:22
*/
@Configuration
@ConditionalOnProperty(name = "server.ssl.enabled", havingValue = "true")
public class HttpsConfig {
/**
* http服务端口
*/
@Value("${server.http.port}")
private Integer httpPort;
/**
* https服务端口
*/
@Value("${server.port}")
private Integer httpsPort;
/**
* http服务模式配置
*/
@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);
});
//二维码地址下载使用http,客户端不支持HTTPS下载升级文件
undertowFactory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addSecurityConstraint(
new SecurityConstraint()
.addWebResourceCollection(new WebResourceCollection()
.addUrlPatterns(
"/serv/v1/index/down",
"/serv/v1/index/version",
"/conf/v1/product/version/down/*"
))
.setTransportGuaranteeType(TransportGuaranteeType.NONE)
.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT)
)
);
// 业务资源请求自动跳转至HTTPS
undertowFactory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addSecurityConstraint(
new SecurityConstraint()
.addWebResourceCollection(new WebResourceCollection().addUrlPattern("/*"))
.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT)
).setConfidentialPortManager(exchange -> httpsPort)
);
return undertowFactory;
}
}
实例分析
上面一个对指定路径拦截,NONE代表不做任何处理并将拦截的路径不转为https协议,下面的则是全量拦截都转为https协议。
配置文件
证书则参考文章头的链接,一般我们项目的证书是阿里上面申请的或者厂商提供的。
结果-------------------》
输入http:127.0.0.1:8080会跳转到https://localhost:8443
配置文件部分参考链接参考链接