首页 > 解决方案 > SpringBoot 2.0 使用 http 和 https 但在 https-port 上将 http 重定向到 https

问题描述

我有一个使用 http 和 https 的 SpringBoot 2.0 应用程序。所以在端口 9080 上它服务于 http 协议和端口 9443 https,它工作正常。我唯一想要的是重定向,如果用户输入例如:http://localhost:9443/e1

把它们加起来:

http://localhost:9080/e1 >> 按预期工作。

https://localhost:9443/e1 >> 按预期工作。

http://localhost:9443/e1 >> 带来错误Bad Request. This combination of host and port requires TLS.,但应该重定向到https://localhost:9443/e1

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    /* HTTP(S) configuration */

    @Value("${http.port}")
    private int httpPort;

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    private Connector createStandardConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        return connector;
    }
}

我的 application.properties 是

server.port=9443
http.port=9080
server.ssl.enabled=true
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=my_passowrd
server.ssl.key-alias=my_alias

也许有人对如何解决它有想法。谢谢,祝你有美好的一天:-)

标签: javaspring-boothttpsssl-certificatekeystore

解决方案


如果您使用的是嵌入式 Tomcat,您可以修改返回的消息以包含重定向标头。

例如对于 Tomcat 9.0.x:

TLSClientHelloExtractor.USE_TLS_RESPONSE = ("HTTP/1.1 302 \r\n"
    + "Content-Type: text/plain;charset=UTF-8\r\n" + "Location: https://" + hostnamePort + "\r\n"
    + "Connection: close\r\n" + "\r\n" + "Bad Request\r\n"
    + "This combination of host and port requires TLS.\r\n"
    + "Please access this URL with HTTPS scheme.\r\n").getBytes(StandardCharsets.UTF_8);

请注意,这是静态值,只能重定向到一个 URL,除非您提供自己的安全通道实现。


推荐阅读