5

如何将http呼叫重定向到httpsin spring-cloud-gateway。我已经在我的网关项目中配置了 https,如This Link中所述。

现在 HTTPS url 工作正常,但此外我需要将所有http调用重定向到https. 我试过这个

但这对我不起作用,因为我没有使用默认http端口 8080,而且我的应用程序在 spring security 上运行。

以下代码显示如何重定向httphttps,但我需要与Netty服务器相同的配置,因为spring-cloud-gateway仅支持 netty..

@Configuration
public class RedirectToHttpsConfig {

    @Value("${server.port}")
    private Integer httpsPort;

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

    /* ################ THIS WILL WORK FINE ################ 
       ################ IF YOU HAVE TOMCAT  ################ 
       ################ AS EMBEDDED SERVER  ################ 
   */
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            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(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(httpPort);
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }

    /* ################ -------- ################ */


    /* ################ HOW TO DO THE ABOVE Configuration
       FOR NETTY SERVER ################ */
    @Bean
    public NettyReactiveWebServerFactory nettyReactiveWebServerFactory(){
        NettyReactiveWebServerFactory netty = nettyReactiveWebServerFactory(){
            NettyServerCustomizer  nettyServerCustomizer = new NettyServerCustomizer() {
                @Override
                public void customize(HttpServerOptions.Builder builder) {
                    **// NOT ABLE TO FIGURE OUT HERE**
                }
            }
        };
    }


}
4

1 回答 1

1

最好的方法是在你的网关前面放一个 apache 并在上面设置一个重写规则。以这种方式运行它有很多优点。它还使您拥有最终用户可以访问的静态 url,如果您有问题或更改 apache 背后的底层技术,您可以将其指向新的服务/url 或其他任何东西。在 Apache 上执行此操作还允许您运行诸如 mod-security 之类的东西。最终它可能只是一个传递(为您的 http-> https 问题使用重写规则),但这比在您的网关中使用代码执行此架构更好。

于 2018-07-11T12:54:38.540 回答