Using HTTPS with GlassFish

The OpenShift forums have been retired.
You can still read and search them, but for help, please post a question on Stack Overflow.

Can anyone tell me how I can use HTTPS with GlassFish ?

It seems like just using HTTPS instead of HTTP works for apps that don't require HTTPS, but for my apps that do require it (by setting <transport-guarantee>CONFIDENTIAL</transport-guarantee> in web.xml), I get a 403 Forbidden when I try to access a page.

For example:

https://glassfish-svanimpe.rhcloud.com/authdemo/ -> This app requires HTTPS for all pages and does not work on OpenShift. Locally I would access it via https://localhost:8181/authdemo/

https://glassfish-svanimpe.rhcloud.com/reminders/api/users -> This webservice does not require HTTPS, yet it does seem to work with either HTTP or HTTPS.

These solutions are for Apache and JBoss, not GlassFish.

With a little help on IRC, I finally got this working !

What I had to do was:

  • Stop using <transport-guarantee>CONFIDENTIAL</transport-guarantee> in web.xml.
  • Use a servlet filter instead to forward HTTP requests to HTTPS. My code for this filter is as follows. Also don't forget to set up this filter in web.xml.
@WebFilter(filterName = "HttpsFilter", urlPatterns = {"/*"})
public class HttpsFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        if (!httpRequest.isSecure() && !httpRequest.getHeader("X-Forwarded-Proto").equals("https")) {
            StringBuilder newUrl = new StringBuilder("https://");
            newUrl.append(httpRequest.getServerName());
            if (httpRequest.getRequestURI() != null) {
                newUrl.append(httpRequest.getRequestURI());
            }
            if (httpRequest.getQueryString() != null) {
                newUrl.append("?").append(httpRequest.getQueryString());
            }
            HttpServletResponse httpResponse = (HttpServletResponse)response;
            httpResponse.sendRedirect(newUrl.toString());
        } else {
            if (chain != null) {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() { }
}

in web.xml:

<filter>
    <filter-name>HttpsFilter</filter-name>
    <filter-class>HttpsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>HttpsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  • Note the use of the x-forwarded-proto header. If I only used request.isSecure(), I had redirect issues.

With this setup, the application behaves as desired, independent of any other applications.

Thanks for posting it back into the post here. Really appreciate it!