【发布时间】:2021-01-09 22:53:15
【问题描述】:
我已经使用 Spring Boot 部署了一个项目。我想将所有流量从 HTTP 重定向到 HTTPS。由于某种原因,重定向不起作用。如果我尝试使用 Chrome 访问 HTTP 网站,我会收到“连接超时”。
现在,如果我尝试通过 HTTPS 访问该网站,Chrome 可以加载该网站。初始加载 HTTPS 网站后,重定向开始工作。即 HTTP 流量成功重定向到 HTTPS。
您可以在隐身模式下使用 chrome 尝试上述场景。
场景 1
- 以隐身方式打开 chrome。访问:http://timelines.co。 Chrome 将超时。
场景 2
- 访问https://timelines.co。 Chrome 将加载该网站。
- 再次访问http://timelines.co。 Chrome 将重定向到https://www.timelines.co
我想知道为什么重定向在场景 1 中不起作用。
这是我的代码的样子:
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
};
}
private Connector redirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
Application.properties
server.port = 443
build.gradle
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.6.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.2.6.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.2.6.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.6.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.2.6.RELEASE'
【问题讨论】:
-
有什么理由不能使用 Spring Security?见Redirect to HTTPS-documentation
-
您甚至无法连接到端口 80 (http)。您确定它在您的 AWS 安全组中打开了吗?
-
@stdunbar -- 你做对了!在附加到实例的安全组中,我的入站规则中没有 HTTP。我添加了 HTTP 规则,现在 HTTP 流量被重定向到 HTTPS。谢谢! 1) 你怎么知道我在 AWS 上? 2) 你知道为什么在场景 2 中重定向在通过 HTTPS 初始加载网站后开始工作吗?如果您希望我接受您的评论作为答案,请将其作为答案发布。再次感谢!
标签: java spring-boot tomcat spring-security https