Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Spring Security headers() by route

Is it possible with spring security to have different header().contentSecurityPolicy("...") settings for different route matchers?

I am currently using the following spring security configuration:

@Configuration
@EnableWebSecurity
public static class MyWebSecurityConfigurerAdapter extends  WebSecurityConfigurerAdapter {
    @Override
    protected final void configure(HttpSecurity httpSecurity) throws Exception     {
        httpSecurity.csrf().disable()
                .rememberMe().disable()
                .headers()
                .cacheControl().disable()
                .referrerPolicy().and()
                .contentSecurityPolicy("default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'").
// followed by .authorizeRequests() section

There is a bug or at least underspecified behaviour in chrome (https://bugs.chromium.org/p/chromium/issues/detail?id=271452) that prevents the browser from displaying PDF documents if the resource is served with a CSP-Header with a strict object-src policy.

To avoid that behaviour, I'd like to provide different contentSecurityPolicy() configuration for different route matchers (in this case one for "../*.pdf" (or even better a matcher that matches on the response content type) and another for all other requests).

like image 307
dwegener Avatar asked Jul 05 '17 08:07

dwegener


1 Answers

This code will create two security filters for two different URLs. Each will have it's own content security policy:

@Configuration
@Order(1)
class PatterWebSecurityConfigurer : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http
            .antMatcher("/pattern")
            .headers().contentSecurityPolicy("directives")
    }
}

@Configuration
@Order(2)
class OtherPatternWebSecurityConfigurer : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http
            .antMatcher("/otherPattern")
            .headers().contentSecurityPolicy("other directives")
    }
}
like image 71
Andrei Nepsha Avatar answered Oct 25 '22 11:10

Andrei Nepsha