Skip to content

Instantly share code, notes, and snippets.

@qerub
Last active November 6, 2022 00:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save qerub/8975333 to your computer and use it in GitHub Desktop.
Save qerub/8975333 to your computer and use it in GitHub Desktop.
Servlet filter for forcing HTTPS when behind a SSL termination proxy that sends X-Forwarded-Proto
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import static java.lang.String.format;
public class HttpsFilter implements Filter {
private boolean enabled;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.enabled = "production".equals(System.getenv("ENV"));
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (!enabled) {
chain.doFilter(request, response);
return;
}
String xfp = httpRequest.getHeader("X-Forwarded-Proto");
if ("https".equals(xfp)) {
httpResponse.setHeader("Strict-Transport-Security", "max-age=60");
chain.doFilter(request, response);
}
else if ("http".equals(xfp)) {
try {
URI uri1 = new URI(httpRequest.getRequestURL().toString());
if (uri1.getPort() >= 0) {
throw new ServletException(format("Only standard ports are supported (given %s)", uri1.getPort()));
}
URI uri2 = new URI("https",
uri1.getUserInfo(),
uri1.getHost(),
/* port: */ -1,
uri1.getPath(),
httpRequest.getQueryString(),
/* fragment: */ null);
httpResponse.sendRedirect(uri2.toString());
}
catch (URISyntaxException e) {
throw new ServletException("Something went wrong with the URIs", e);
}
}
else {
throw new ServletException(format("Unsupported value for X-Forwarded-Proto: %s", xfp));
}
}
}
@qerub
Copy link
Author

qerub commented Feb 13, 2014

Server filters are a PITA compared to Rack/Ring middleware. :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment