I've found many question about enforcing HTTPS under heroku but no response are about the java.
Here are the link I found :
Scala : http://www.andersen-gott.com/2012/03/using-unfiltered-and-https-on-heroku.html
Rails : Rails - How to Redirect from http://example.com to https://www.example.com
Please note that I am using Spring MVC 3.1 so I would prefer a solution based on WebMvcConfigurerAdapter.addInterceptors(InterceptorRegistry registry)
Here is a Servlet Filter that redirects all non-https requests to https:
package com.jamesward;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HttpsEnforcer implements Filter {
private FilterConfig filterConfig;
public static final String X_FORWARDED_PROTO = "x-forwarded-proto";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (request.getHeader(X_FORWARDED_PROTO) != null) {
if (request.getHeader(X_FORWARDED_PROTO).indexOf("https") != 0) {
response.sendRedirect("https://" + request.getServerName() + (request.getPathInfo() == null ? "" : request.getPathInfo()));
return;
}
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
// nothing
}
}
I did this as a Servlet Filter because I couldn't get a Spring Interceptor to intercept the static asset (resource) requests.
Full source: https://github.com/jamesward/springmvc-https-enforcer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With