Spring Boot将HTTP重定向到HTTPS

问题描述:

对于基于Spring Boot的应用程序,我在application.properties上配置了ssl属性,请参阅我的配置:

For Spring Boot based application I have configurared ssl properties at application.properties, see my configuration here:

server.port=8443
server.ssl.key-alias=tomcat
server.ssl.key-password=123456
server.ssl.key-store=classpath:key.p12
server.ssl.key-store-provider=SunJSSE
server.ssl.key-store-type=pkcs12

我在Application.class上添加了连接,比如

And I have added conection at Application.class, like

@Bean
public EmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
    final TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
    factory.addAdditionalTomcatConnectors(this.createConnection());
    return factory;
}

private Connector createConnection() {
    final String protocol = "org.apache.coyote.http11.Http11NioProtocol";
    final Connector connector = new Connector(protocol);

    connector.setScheme("http");
    connector.setPort(9090);
    connector.setRedirectPort(8443);
    return connector;
}

但当我尝试以下时间

http://127.0.0.1:9090/

重定向到

https://127.0.0.1:8443/

未执行。谁遇到过类似的问题?

is not performed. Who faced a similar problem?

要使Tomcat执行重定向,您需要使用一个或多个安全约束对其进行配置。您可以通过使用 TomcatEmbeddedServletContainerFactory 子类对 Context 进行后处理来实现此目的。

For Tomcat to perform a redirect, you need to configure it with one or more security constraints. You can do this by post-processing the Context using a TomcatEmbeddedServletContainerFactory subclass.

例如:

TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
    @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);
    }
};

由于 CONFIDENTIAL / * ,这将导致Tomcat将每个请求重定向到HTTPS。如果您需要更多控制重定向和不重定向的内容,您可以配置多个模式和多个约束。

Due to CONFIDENTIAL and /*, this will cause Tomcat to redirect every request to HTTPS. You can configure multiple patterns and multiple constraints if you need more control over what is and is not redirected.