Spring Content Security Security

assuming a working example of greeting the world of spring and spring mvc.

when I take a trace using wirehark, I see the following flags in 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 X-Frame-Options does almost the same job, but still it makes me sleep better. Now I assume that I will need to do this under the function to configure my spring security configuration, however I do not know exactly how, for example, I put .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(); } 
+6
source share
2 answers

Just use the addHeaderWriter method as follows:

 @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'")) // ... } } 

Please note that as soon as you specify any headings that should be included, only those headings will be included.

To enable the default headers, you can:

 http .headers() .contentTypeOptions() .xssProtection() .cacheControl() .httpStrictTransportSecurity() .frameOptions() .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'")) // ... 

You can refer to spring security documentation .

+12
source

While the approach with StaticHeadersWriter works, a new method can be used in the latest versions of Spring Security:

 headers() .contentSecurityPolicy("script-src 'self'"); 

See the documentation for more details: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/headers.html#headers-csp-configure

+3
source

Source: https://habr.com/ru/post/970382/


All Articles