Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefered way to redirect http connection to https in Dropwizard

I'd like to redirect incoming http connections to https in Dropwizard, preferably togglable in a config file (e.g. with a YAML file, like other connection attributes). [I've seen this question, and I'm reasonably certain that it's not a solution]

A solution I've found in several places involves hooking in a Filter that checks the schema, and if it finds "http", calls sendRedirect with a modified URL. This involves hardcoding the behavior to make this always happen though.

If I extend the HttpConnectorFactory, it seems like I could add configuration in the YAML for whether I want the redirection to happen. However, it's unclear to me how complicated it will be to add an attribute without breaking other code.

This seems like a common task; is there a standard, "preferred" way to do this? I would have expected Dropwizard to have elegant built-in support, like Jetty does, but I can't find it.

like image 450
Cannoliopsida Avatar asked May 28 '14 03:05

Cannoliopsida


2 Answers

I don't know that there's a "preferred" way to do this but how about something like this (for 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());
  }
  //...      
}

You'd just need to add a boolean to your application configuration and then you could easily switch https forwarding with your YAML.

like image 109
condit Avatar answered Oct 23 '22 15:10

condit


You can use the redirect bundle at

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

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

Above HttpsRedirect is constructed with false for allowPrivateIps which makes testing things locally possible. HttpsRedirect docs has plenty of information on this.

like image 34
Gorky Avatar answered Oct 23 '22 16:10

Gorky