SpringBoot 2.0使用http和https,但是将HTTP重定向到https-port上的https

时间:2019-03-07 14:37:42

标签: java spring-boot https ssl-certificate keystore

我有一个使用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

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

1 个答案:

答案 0 :(得分:1)

如果您使用嵌入式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。