Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding security headers in response using spring security

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?

like image 510
San Avatar asked Mar 11 '15 19:03

San


People also ask

How do I create a security header in spring boot?

Simply adding the <headers> element with no child elements will automatically add Cache Control and quite a few other protections. However, if you only want cache control, you can enable this feature using Spring Security's XML namespace with the <cache-control> element and the headers@defaults-disabled attribute.

How do you set a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

How do I add security to my Spring application?

For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file. Maven users can add the following dependency in the pom. xml file. Gradle users can add the following dependency in the build.


1 Answers

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).

like image 170
Neil McGuigan Avatar answered Sep 23 '22 01:09

Neil McGuigan