Content-Security-Policy Spring Security
content-security-policy, security, spring, spring-security
Solution
Simply use the addHeaderWriter method like this:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.headers()
.addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
// ...
}
}
Note that as soon as you specify any headers that should be included, then only those headers will be include.
To include the default headers you can do:
http
.headers()
.contentTypeOptions()
.xssProtection()
.cacheControl()
.httpStrictTransportSecurity()
.frameOptions()
.addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
// ...
You can refer to the spring security documentation.
Problem
assuming a working hello world example of spring security and spring mvc. when i take a trace with wireshark i see the following flags on the http request ``` X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0 Strict-Transport-Security: max-age=31536000 ; includeSubDomains X-Frame-Options: DENY Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; Path=/; Secure; HttpOnly ``` i would like to add this to my headers: ``` Content-Security-Policy: script-src 'self' ``` I know that the X-Frame-Options is doing almost the same job, but still it makes me sleep better. Now i guess that i would need to do it under the configure function of my spring security configuration however i do not know how exactly, i.e. i suppose .headers().something.something(self) ``` @Override protected void configure(HttpSecurity http) throws Exception { http // .csrf().disable() // .headers().disable() .authorizeRequests() .antMatchers( "/register", "/static/**", "/h2/**", "/resources/**", "/resources/static/css/**", "/resources/static/img/**" , "/resources/static/js/**", "/resources/static/pdf/**" ).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } ```