Spring Security vulnerability protection-HTTP security response header

1. Default Security Header

Spring Security provides a default set of secure HTTP response headers to provide secure defaults. While each of these headers is considered a best practice, it should be noted that not all clients use these headers, so additional testing is encouraged.

You can customize specific headers. For example, suppose you want to use the default value, but you want to specify SAMEORIGIN for X-Frame-Options.

You can do this with the following configuration.

Customize Default Security Headers

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.frameOptions(frameOptions -> frameOptions
.sameOrigin()
)
);
return http.build();
}
}

If you don’t want to add a default value and want explicit control over what should be used, you can disable the default value. The following code listing shows how to do this.

If you are using Spring Security’s configuration, only Cache Control is added below.

Customize Cache Control Headers

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
// do not use any default headers unless explicitly listed
.defaultsDisabled()
.cacheControl(withDefaults())
);
return http.build();
}
}

If necessary, you can disable all HTTP security response headers with the following configuration.

Disable All HTTP Security Headers

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers.disable());
return http.build();
}
}

2. Cache Control

Spring Security includes the Cache Control header by default.

However, if you really want to cache a specific response, your application can optionally call HttpServletResponse.setHeader(String,String) to override the header set by Spring Security. You can use this to ensure that content (such as CSS, JavaScript, and images) is cached correctly.

When you use Spring Web MVC, this is usually done in your configuration. You can find details on how to do this in the Static Resources section of the Spring reference documentation

If necessary, you can also disable Spring Security’s cache control HTTP response headers.

Cache Control Disabled

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.cacheControl(cache -> cache.disable())
);
return http.build();
}
}

3. Content Type Options

Spring Security includes the Content-Type header by default. However, you can disable it.

Content Type Options Disabled

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable())
);
return http.build();
}
}

4. HTTP Strict Transport Security (HSTS)

By default, Spring Security provides the Strict Transport Security header. However, you can explicitly customize the results. The following example explicitly provides HSTS.

Strict Transport Security

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.preload(true)
.maxAgeInSeconds(31536000)
)
);
return http.build();
}
}

5. HTTP Public Key Pinning (HPKP)

Spring Security provides servlet support for HTTP Public Key Pinning, but it is no longer recommended.

You can enable HPKP header with the following configuration.

HTTP Public Key Pinning

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.httpPublicKeyPinning(hpkp -> hpkp
.includeSubDomains(true)
.reportUri("https://example.net/pkp-report")
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd + 2eRQozYqqbQ2yXLVKB9 + xcprMF + 44U1g=")
)
);
return http.build();
}
}

6. X-Frame-Options

By default, Spring Security instructs the browser to block reflected XSS attacks by using X-Frame-Options.

For example, the following configuration specifies that Spring Security should no longer instruct the browser to block this content.

X-Frame-Options: SAMEORIGIN

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.frameOptions(frameOptions -> frameOptions
.sameOrigin()
)
);
return http.build();
}
}

7. X-XSS-Protection

By default, Spring Security instructs the browser to disable the XSS Auditor by using the X-XSS-Protection header. However, you can change this default value. For example, the following configuration specifies that Spring Security instructs compatible browsers to enable filtering and block this content.

X-XSS-Protection Customization

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.xssProtection(xss -> xss
.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK)
)
);
return http.build();
}
}

8. Content Security Policy (CSP)

Spring Security does not add a Content Security Policy by default because it is impossible to know a reasonable default without understanding the context of the application. Web application authors must declare security policies (or policies) to enforce or monitor protected resources.

Consider the following security strategies.

Content Security Policy Example

Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/</ pre>
<p>Given the previous security policy, you can enable the CSP header.</p>
<p><em>Content Security Policy</em></p>
<ul><li><strong>Java</strong></li></ul>
<pre>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
)
);
return http.build();
}
}

To enable the CSP report-only header, provide the following configuration.

Content Security Policy Report Only

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
.reportOnly()
)
);
return http.build();
}
}

9. Referrer Policy

Spring Security does not add the Referrer Policy header by default. You can enable the Referer Policy header by using configuration.

Referrer Policy

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.referrerPolicy(referrer -> referrer
.policy(ReferrerPolicy.SAME_ORIGIN)
)
);
return http.build();
}
}

10. Feature Policy

Spring Security does not add the Feature Policy header by default. Consider the Feature-Policy header below.

Feature-Policy Example

Feature-Policy: geolocation 'self'

You can enable the previous feature policy header by using the following configuration

Feature-Policy

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.featurePolicy("geolocation 'self'")
);
return http.build();
}
}

11. Permissions Policy

Spring Security does not add the Permissions Policy header by default. Consider the following Permissions-Policy header.

Permissions-Policy Example

Permissions-Policy: geolocation=(self)

You can enable the previous permissions policy header using the following configuration.

Permissions-Policy

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.permissionsPolicy(permissions -> permissions
.policy("geolocation=(self)")
)
);
return http.build();
}
}

12. Clear Site Data

Spring Security does not add the Clear-Site-Data header by default. Consider the following Clear-Site-Data header.

Clear-Site-Data Example

Clear-Site-Data: "cache", "cookies"

You can send the previous header on logout with the following configuration.

Clear-Site-Data

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.logout((logout) -> logout
                .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(CACHE, COOKIES)))
);
return http.build();
}
}

13. Custom Header

Spring Security has mechanisms to easily add more common security headers to your application. However, it also provides hooks to add custom headers.

1. Static Header

Sometimes, you may want to inject unsupported custom security headers into your application. Consider the following custom security header.

X-Custom-Security-Header: header-value

Given the previous header information, you can add header information to the response by using the following configuration.

StaticHeadersWriter

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value"))
);
return http.build();
}
}

2. HeadersWriter

When the namespace or Java configuration does not support the header you want, you can create a custom HeadersWriter instance or even provide a custom HeadersWriter implementation.

The next example uses a custom instance of XFrameOptionsHeaderWriter. If you want to configure X-Frame-Options explicitly, you can do so with the following configuration.

Headers Writer

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
);
return http.build();
}
}

3. DelegatingRequestMatcherHeaderWriter

Sometimes, you may want to write a header only for certain requests. For example, maybe you just want to protect your login page. You can use DelegatingRequestMatcherHeaderWriter to do this.

The following configuration example uses DelegatingRequestMatcherHeaderWriter.

DelegatingRequestMatcherHeaderWriter Java Configuration

  • Java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
RequestMatcher matcher = new AntPathRequestMatcher("/login");
DelegatingRequestMatcherHeaderWriter headerWriter =
new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter());
http
// ...
.headers(headers -> headers
.frameOptions(frameOptions -> frameOptions.disable())
.addHeaderWriter(headerWriter)
);
return http.build();
}
}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Network Skill TreeHomepageOverview 41960 people are learning the system