Adding security headers in response using spring security

San picture San · Mar 11, 2015 · Viewed 10.1k times · Source

Am using spring security version 3.2. Am adding headers such as X-Frame-options, X-content-type-options in the response headers of the authenticated request.

<sec:http auto-config="false">
     <sec:headers>
          <sec:frame-options policy="DENY" />
          <sec:content-type-options  />
          <sec:xss-protection enabled="true" block="true" />
     </sec:headers>
</sec:http>

but those headers are not get adding in the security none request.

<sec:http security="none" pattern="/spring/loginpage" />

what might be the reason?

Answer

Neil McGuigan picture Neil McGuigan · Mar 11, 2015

Because if there's no security on that pattern, then Spring Security isn't activated.

Make your own Interceptor, like this:

public class SecurityHeadersInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        response.setHeader("Strict-Transport-Security","max-age=31536000 ; includeSubDomains");
        response.setHeader("X-Content-Type-Options", "nosniff");
        response.setHeader("X-Frame-Options", "DENY");
        response.setHeader("X-XSS-Protection", "1; mode=block");
        response.setHeader("Content-Security-Policy", "default-src 'self'");

        super.postHandle(request, response, handler, modelAndView);
    }
}

In mvc-dispatcher-servlet.xml add:

<mvc:interceptor>
  <mvc:mapping path="/**"/>
  <bean class="com.example.interceptor.SecurityHeadersInterceptor"/>
</mvc:interceptor>

You should set Cache-Control: no-store, must-revalidate on any private responses too (incl if contains CSRF token, like a login form).