【问题标题】:Prefered way to redirect http connection to https in Dropwizard在 Dropwizard 中将 http 连接重定向到 https 的首选方式
【发布时间】:2014-07-17 03:25:45
【问题描述】:

我想将传入的 http 连接重定向到 Dropwizard 中的 https,最好在配置文件中切换(例如,使用 YAML 文件,如其他连接属性)。 [我见过this question,我有理由确定这不是解决方案]

我在severalplaces 中找到的一个解决方案涉及挂钩检查架构的Filter,如果找到“http”,则使用修改后的 URL 调用 sendRedirect。这涉及对行为进行硬编码以使这种情况始终发生。

如果我扩展HttpConnectorFactory,似乎我可以在 YAML 中添加配置,以确定是否希望发生重定向。但是,我不清楚在不破坏其他代码的情况下添加属性会有多复杂。

这似乎是一项常见的任务;有没有标准的“首选”方式来做到这一点?我本来希望 Dropwizard 有优雅的内置支持,like Jetty does,但我找不到。

【问题讨论】:

    标签: java redirect https http-redirect dropwizard


    【解决方案1】:

    我不知道有什么“首选”方式可以做到这一点,但是这样的事情怎么样(对于 Dropwizard 0.7.0):

    void addHttpsForward(ServletContextHandler handler) {
      handler.addFilter(new FilterHolder(new Filter() {
    
        public void init(FilterConfig filterConfig) throws ServletException {}
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
          StringBuffer uri = ((HttpServletRequest) request).getRequestURL();
          if (uri.toString().startsWith("http://")) {
            String location = "https://" + uri.substring("http://".length());
            ((HttpServletResponse) response).sendRedirect(location);
          } else {
            chain.doFilter(request, response);
          }
        }
    
        public void destroy() {}
      }), "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    
    @Override
    public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
      //...
      if (configuration.forwardHttps()) {
        addHttpsForward(environment.getApplicationContext());
      }
      //...      
    }
    

    您只需要在应用程序配置中添加一个布尔值,然后您就可以使用 YAML 轻松切换 https 转发。

    【讨论】:

      【解决方案2】:

      您可以在

      处使用重定向包

      https://github.com/dropwizard-bundles/dropwizard-redirect-bundle

      @Override
      public void initialize(final Bootstrap<PrmCatchConfiguration> bootstrap) {
          bootstrap.addBundle(new RedirectBundle(new HttpsRedirect(false)));
      

      HttpsRedirect 之上是用 false 构造的 allowPrivateIps ,这使得本地测试成为可能。 HttpsRedirect 文档对此有大量信息。

      【讨论】:

        猜你喜欢
        • 2018-05-03
        • 2011-07-15
        • 2019-02-23
        • 2016-05-15
        • 2017-11-13
        • 1970-01-01
        • 1970-01-01
        • 2012-06-29
        • 2015-03-11
        相关资源
        最近更新 更多