java - 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
也许有人对如何解决它有想法。谢谢,祝你有美好的一天:-)
解决方案
如果您使用的是嵌入式 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,除非您提供自己的安全通道实现。
推荐阅读
- javascript - 通过类名查找元素和通过 CSS 选择器查找元素有什么区别?
- java - 在 Felix 中启动和运行 CXF (JAX-RS) Web 资源的最低要求是什么?
- sql-server - SQL Server 崩溃
- iis - .NET Core WebAPI IIS 部署
- git - git push -u origin master 命令未反映 github 上的更改
- html - Oracle Virtualbox 网络 SPAN/镜像端口
- javascript - 为什么我的 if & else 条件不能正常工作?
- java - 将json字符串反序列化为具有杰克逊字符串属性的对象
- python - 带有 sqlalchemy 的 Flask 应用程序尝试使用 Flask-APScheduler 安排作业
- python - 如何计算子串中元音的数量?