有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java更喜欢在Dropwizard中将http连接重定向到https

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

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

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

这似乎是一项共同的任务;有没有一个标准的“首选”方法来做到这一点?我本以为Dropwizard会有优雅的内置支持,但我找不到


共 (2) 个答案

  1. # 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. # 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 for allowPrivateIps构造的,这使得本地测试成为可能。HttpsRedirect docs对此有大量信息