Undertow设置80重定向443

undertow

#1

Undertow设置80重定向443

网上找的代码(原代码花里胡哨各种lambda表达式),我优化了一下,亲测可行。

UndertowConfiguration

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
import io.undertow.Undertow.Builder;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ConfidentialPortManager;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.api.WebResourceCollection;

@Configuration
public class UndertowConfiguration implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {

	// https 端口
	@Value("${server.port}")
	private Integer port;

	// 是否开启 https
	@Value("${server.ssl.enabled:false}")
	private Boolean sslEnable;

	@Override
	public void customize(UndertowServletWebServerFactory factory) {

		if (this.sslEnable) {
			factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
				@Override
				public void customize(Builder builder) {
					// 监听80
					builder.addHttpListener(80, "0.0.0.0");
				}
			});
			factory.addDeploymentInfoCustomizers(new UndertowDeploymentInfoCustomizer() {
				@Override
				public void customize(DeploymentInfo deploymentInfo) {
					SecurityConstraint securityConstraint = new SecurityConstraint();
					WebResourceCollection webResourceCollection = new WebResourceCollection();
					webResourceCollection.addUrlPattern("/*");
					securityConstraint.addWebResourceCollection(webResourceCollection);
					securityConstraint.setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL);
					securityConstraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
					deploymentInfo.addSecurityConstraint(securityConstraint);
					deploymentInfo.setConfidentialPortManager(new ConfidentialPortManager() {
						@Override
						public int getConfidentialPort(HttpServerExchange exchange) {
							return port;
						}
					});
				}
			});
		}
	}
}