【问题标题】:How to redirect HTTP to HTTPS in spring cloud gatewaySpring Cloud Gateway中如何将HTTP重定向到HTTPS
【发布时间】:2018-12-11 12:11:45
【问题描述】:

如何将http 呼叫重定向到spring-cloud-gateway 中的https。我已按照This Link 中的说明在我的网关项目中配置了 https。

现在 HTTPS 网址工作正常,但此外我需要将所有 http 调用重定向到 https。我试过This

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

以下代码显示如何将http 重定向到https,但我需要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**
                }
            }
        };
    }


}

【问题讨论】:

    标签: spring-cloud-gateway


    【解决方案1】:

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

    【讨论】:

    • 最好的方法是在 apache 上做 SSL,而不是在网关上,但这不是网关问题的答案
    猜你喜欢
    • 2022-10-19
    • 1970-01-01
    • 2021-07-30
    • 2018-08-09
    • 2014-12-26
    • 2019-08-03
    • 2015-04-23
    • 2010-09-05
    相关资源
    最近更新 更多