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();
}
The Content Security Policy (CSP) is a security standard that helps protect and mitigate content injection attacks such as cross-site scripting (XSS), clickjacking, and more. You can use it to protect your Spring web applications by enabling specific HTTP headers.
Example CSP Header with Java By referencing the HTTP Servlet API, we can use the addHeader method of the HttpServletResponse object. response. addHeader("Content-Security-Policy", "default-src 'self'"); Your policy will go inside the second argument of the addHeader method in the example above.
Why use the Content Security Policy? The primary benefit of CSP is preventing the exploitation of cross-site scripting vulnerabilities. When an application uses a strict policy, an attacker who finds an XSS bug will no longer be able to force the browser to execute malicious scripts on the page.
While the approach with StaticHeadersWriter
works, in the newest versions of Spring Security it's possible to use a special method:
headers()
.contentSecurityPolicy("script-src 'self'");
See documentation for details: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/headers.html#headers-csp-configure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With