4

As I have an Apache Webserver which does ProxyPass to the Glassfish server, the latter does not know that the customers are talking "https".

Thus when using things like

return "shop.xhtml?faces-redirect=true";

the generated HTTP Location: header contains a "http://" URL.

I've read JSF redirects from HTTPS to HTTP but found this solution not very elegant. Is there a way to tell Glassfish that this or all incoming requests are https so that I don't have to fiddle with the generated Navigation rules?

Community
  • 1
  • 1
lathspell
  • 3,040
  • 1
  • 30
  • 49

1 Answers1

2

You may try to add some request header which can be interpreted on java side, for example 'X-redirect-to-https'. Then create filter that will wrap HttpServletResponse, and in that wrapper override sendRedirect method to replace http with https in redirect URL when 'X-redirect-to-https' header is present.

Code (a little messy, but illustrates a solution) adapted from: http://javahunter.wordpress.com/2011/06/01/why-does-https-become-http-on-a-sendredirect/

@WebFilter("/*")
public class HttpsSendRedirectFilter implements Filter {

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
   }

   @Override
   public void destroy() {
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
         ServletException {
      chain.doFilter(request, new HttpsRedirectResponseWrapper((HttpServletRequest) request,
            (HttpServletResponse) response));
   }
}

public class HttpsRedirectResponseWrapper extends HttpServletResponseWrapper {

   private HttpServletRequest req;
   private String prefix = null;

   public HttpsRedirectResponseWrapper(HttpServletRequest req, HttpServletResponse res) {
      super(res);
      this.req = req;
      prefix = getPrefix(req);
   }

   @Override
   public void sendRedirect(String location) throws IOException {
      String finalurl = null;

      if (isUrlAbsolute(location)) {
         finalurl = location;
      } else {
         finalurl = fixForScheme(prefix + location);
      }
      super.sendRedirect(finalurl);
   }

   public boolean isUrlAbsolute(String url) {
      String lowercaseurl = url.toLowerCase();
      if (lowercaseurl.startsWith("http") == true) {
         return true;
      } else {
         return false;
      }
   }

   public String fixForScheme(String url) {
      if (this.req.getHeader("X-redirect-to-https") != null) {
         return url.replaceFirst("http", "https");
      } else {
         return url;
      }
   }

   public String getPrefix(HttpServletRequest request) {
      StringBuffer str = request.getRequestURL();
      String url = str.toString();
      String uri = request.getRequestURI();
      int offset = url.indexOf(uri);
      String prefix_t = url.substring(0, offset);
      return prefix_t;
   }
}
povder
  • 187
  • 1
  • 12