javaspringsecuritytomcathsts

Add HSTS feature to Tomcat


Trust you all well.

My web application run on tomcat 6.0.43 and do not use apache or nginx at front.

I'm already enforce my web from http redirect to https using:

  1. URL Redirect at ../webapps/ROOT/index.jsp

<% response.sendRedirect("https://www.epi.com.my/portal/"); %>

  1. ../webapps/myapp/WEB-INF/web.xml
<security-constraint>
<web-resource-collection>
  <web-resource-name>Protected Context</web-resource-name>
     <url-pattern>/*</url-pattern>
 </web-resource-collection>
 <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint></security-constraint>

Where to add such code below

Header add Strict-Transport-Security "max-age=15768000"

OR Is tomcat did not have this feature? Or I need to modify in every my java web app controller.


Solution

  • You can add it using a filter. Add the following snippet to web.xml:

    <filter>
        <filter-name>HSTSFilter</filter-name>
        <filter-class>security.HSTSFilter</filter-class>
    </filter>
    

    And then create a filter in your webapp:

    package security;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    
    public class HSTSFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
            HttpServletResponse resp = (HttpServletResponse) res;
    
            if (req.isSecure())
                resp.setHeader("Strict-Transport-Security", "max-age=31622400; includeSubDomains");
    
            chain.doFilter(req, resp);
        }
    }
    

    Its also possible to add the filter using the global web.xml (conf/web.xml).