How to add X-Frame-Options to just some responses in Spring Security 3.2

1.5k views Asked by At

I would like to add X-Frame-Options header to all but some pages in my Spring application. Spring Security 3.2 offers nice capability to add that header to all responses via <headers> <frame-options /> </headers> configuration.

But could it be possible to exclude this header from some paths? I considered subclassing XFrameOptionsHeaderWriter and do some path regexp matching inside, but it seems a bit ugly. Maybe there is more convenient way to accomplish this?

1

There are 1 answers

0
ronkot On BEST ANSWER

I found out how to do it with XML configuration:

<http>
    <headers>
        <header ref="xFrameOptionsHeaderWriter" />
    </headers>
</http>


<beans:bean id="xFrameOptionsHeaderWriter" class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter">
    <!-- Argument 1: RequestMatcher. This matcher will match all but some paths. -->
    <beans:constructor-arg> 
        <beans:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
            <beans:constructor-arg>
                <beans:bean class="org.springframework.security.web.util.matcher.OrRequestMatcher">
                    <beans:constructor-arg>
                        <beans:list>
                            <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher" c:pattern="/**/some-path/**" />
                            <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher" c:pattern="/**/another-path/**" />
                        </beans:list>
                    </beans:constructor-arg>
                </beans:bean>
            </beans:constructor-arg>
        </beans:bean>
    </beans:constructor-arg>

    <!-- Argument 2: HeaderWriter -->
    <beans:constructor-arg>
        <beans:bean  class="org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter" c:frameOptionsMode="SAMEORIGIN" />
    </beans:constructor-arg>
</beans:bean>