Spring
Spring

Reputation: 11835

How to Add Spring Security HTTP Response Headers

Starting with Spring 3.2 I can simply add this to my security xml:

 <security:headers>
    <security:frame-options
            policy="SAMEORIGIN" />
</security:headers>

But this is not supported in Spring version 3.1, any workaround for this without having to upgrade the version?

This is documentation for version 3.1:

http://docs.spring.io/spring-security/site/docs/3.1.3.RELEASE/reference/springsecurity.html

Upvotes: 1

Views: 3796

Answers (1)

chimmi
chimmi

Reputation: 2085

I believe XFrameOptionsHeaderWriter implements logic behind this configuration. It was introduced in Spring 3.2, nothing similar exist prior to that version.

If you want to implement this yourself, you can use a simple filter:

public class XFrameOptionsHeaderFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        filterChain.doFilter(request, response);
    }

}

You need to create a bean for this class in your application context:

<bean id="xFrameOptionsHeaderFilter" class="your.package.XFrameOptionsHeaderFilter"/>

And then register the filter in your web.xml:

<filter>  
    <filter-name>xFrameOptionsHeaderFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>xFrameOptionsHeaderFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Upvotes: 3

Related Questions