Sub topic 14
Security headers and hardening checklist
This chapter covers the HTTP response headers Spring Security adds, how to tune them for a REST API, and a checklist for the rest of the application. It assumes you have a working SecurityFilterChain for a stateless API, as built in earlier chapters. You should also know how CORS, CSRF and 401/403 handling fit into that chain. Header tuning matters less for pure JSON APIs than for web pages. Even so, a few headers cost nothing and limit the damage if a response is ever rendered by a browser.
What Spring Security adds by default
A filter called HeaderWriterFilter sits early in the filter chain. It wraps the response and writes a set of headers when the response is committed. You get these with no configuration.
| Header | Default value | Purpose |
|---|---|---|
| `X-Content-Type-Options` | `nosniff` | Stops browsers from guessing a content type that differs from the declared one. |
| `Cache-Control` | `no-cache, no-store, max-age=0, must-revalidate` | Keeps authenticated responses out of shared and browser caches. |
| `Pragma` | `no-cache` | The same cache rule for old HTTP/1.0 clients. |
| `Expires` | `0` | The same cache rule for old HTTP/1.0 clients. |
| `Strict-Transport-Security` | `max-age=31536000 ; includeSubDomains` | Tells browsers to use HTTPS only. Written only on HTTPS requests. |
| `X-Frame-Options` | `DENY` | Blocks the response from being shown in a frame. |
| `X-XSS-Protection` | `0` | Turns off the old browser XSS filter, which caused its own vulnerabilities. |
Spring Security does not add Content-Security-Policy, Referrer-Policy or Permissions-Policy by default. You add those yourself.
Headers are written when the response is committed, so error responses from the security filters carry them too. A 401 from your own entry point has the same headers as a 200.
Tuning headers for an API
An API returns JSON, not HTML, so the most useful content security policy is the strictest one. default-src 'none' tells a browser not to load anything from the response. frame-ancestors 'none' stops it from being embedded.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
@Configuration
@EnableWebSecurity
public class HardenedSecurityConfig {
@Bean
SecurityFilterChain hardenedChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'none'; frame-ancestors 'none'"))
.frameOptions(frame -> frame.deny())
.referrerPolicy(ref -> ref.policy(ReferrerPolicy.NO_REFERRER))
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000))
.addHeaderWriter(new StaticHeadersWriter(
"Permissions-Policy", "geolocation=(), camera=(), microphone=()")))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Calling headers(...) with a lambda keeps the other defaults. Each nested call changes one header. Use headers.disable() only if a proxy or gateway sets every header for you, and then verify that it does.
StaticHeadersWriter is the stable way to add any header Spring Security has no dedicated method for. It works the same across Spring Security 6 versions.
Relaxing cache headers on purpose
The default Cache-Control: no-store is right for authenticated data. For a public, rarely changing resource, you can set your own caching in the controller. Spring Security does not overwrite a Cache-Control header that is already set. Only do this for responses that are identical for every caller. A cached per-user response is a data leak.
HTTPS and HSTS
Strict-Transport-Security is ignored over plain HTTP, so Spring Security writes it only when the request is secure. Behind a load balancer that terminates TLS, your application sees plain HTTP and never writes the header. Fix this by telling Spring to trust the forwarded headers:
server.forward-headers-strategy=framework
server.error.include-stacktrace=never
server.error.include-message=never
server.error.include-binding-errors=never
management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=neverThe first line makes the request report https when the proxy sends X-Forwarded-Proto: https. Use this only when the proxy is trusted and strips these headers from client requests. Otherwise a client can forge them.
The server.error.* lines stop Spring Boot's default error body from leaking exception messages and stack traces. The management.* lines limit which actuator endpoints are reachable over the web.
To redirect HTTP to HTTPS from inside the application, add http.requiresChannel(c -> c.anyRequest().requiresSecure()) to the chain. Most deployments do this at the proxy instead. If you use it behind a proxy without the forwarded-headers setting above, every request looks insecure and you get a redirect loop.
Locking down actuator endpoints
Actuator endpoints such as /actuator/env and /actuator/heapdump expose configuration and memory contents. Expose only what you need, and put the rest behind a role. Spring Boot provides EndpointRequest to match them.
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class ActuatorSecurityConfig {
@Bean
@Order(1)
SecurityFilterChain actuatorChain(HttpSecurity http) throws Exception {
http
.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.anyRequest().hasRole("ADMIN"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
}This needs spring-boot-starter-actuator on the classpath. The @Order(1) makes this chain match first, so the API chain only sees non-actuator requests. When you have several chains, give each a distinct order, and make sure the last one has no securityMatcher so it catches everything else.
Verifying headers in a test
Headers are easy to break by accident, for example when someone replaces the chain or adds headers.disable(). A short test catches that. This one uses a minimal controller and MockMvc.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RestController
class PingController {
@GetMapping("/public/ping")
String ping() {
return "pong";
}
}
@WebMvcTest(PingController.class)
@Import(HardenedSecurityConfig.class)
class SecurityHeadersTest {
@Autowired
MockMvc mvc;
@Test
void sendsHardenedHeaders() throws Exception {
mvc.perform(get("/public/ping").secure(true))
.andExpect(status().isOk())
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Referrer-Policy", "no-referrer"))
.andExpect(header().string("Content-Security-Policy",
"default-src 'none'; frame-ancestors 'none'"))
.andExpect(header().exists("Strict-Transport-Security"));
}
@Test
void errorResponsesAlsoCarryHeaders() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized())
.andExpect(header().string("X-Content-Type-Options", "nosniff"));
}
}The .secure(true) call marks the mock request as HTTPS, which is what makes the HSTS header appear. The second test confirms that a 401 produced by the security filters still has the headers.
Hardening checklist
Work through this list before you ship. Each item names the chapter or setting that covers it.
- Deny by default. End every chain with
anyRequest().authenticated()oranyRequest().denyAll(). Rules are matched in order and the first match wins, so put specific paths before general ones. - Use HTTPS everywhere. Terminate TLS at the proxy or the app, set
server.forward-headers-strategy, and confirm HSTS appears on responses. - Hash passwords with a modern encoder. Use
BCryptPasswordEncoderorDelegatingPasswordEncoder. Never store or log plain passwords. - Keep secrets out of the repository. Read keys, client secrets and database passwords from environment variables or a secrets manager.
- Validate tokens fully. For JWTs, configure the issuer so the signature, expiry and issuer are checked. Add an audience check when more than one API trusts the same issuer. Keep access tokens short-lived.
- Name CORS origins explicitly. Avoid
*, and never combine a wildcard origin with credentials. - Disable CSRF only for stateless token APIs. If any endpoint relies on a session cookie, keep CSRF protection on.
- Hide internals in errors. Turn off stack traces and messages in error bodies, and return the same 401 for an unknown user and a wrong password.
- Limit actuator exposure. Expose only
healthandinfopublicly, and require a role for everything else. - Authorize at two levels. Use path rules for coarse access and
@PreAuthorizefor object-level checks such as "only the owner". - Throttle authentication endpoints. Spring Security has no built-in rate limiter. Add one at the gateway or with a filter, so password guessing is slow.
- Log security events without secrets. Record failed logins and access denials. Never log passwords, tokens or full
Authorizationheaders. - Keep dependencies current. Update Spring Boot patch releases promptly and scan dependencies for known vulnerabilities in CI.
- Test the negative cases. Cover anonymous, wrong-role and missing-scope requests, as you did in the testing chapter.
Common mistakes
- Missing HSTS in production. The header works locally over HTTPS but disappears behind a proxy that terminates TLS. Check
server.forward-headers-strategy. - Duplicate headers. If both the proxy and Spring Security set
X-Frame-Options, browsers may see two values and ignore both. Pick one place to set each header. - One CSP for everything. A policy for JSON responses breaks HTML pages, and a loose policy on an API gives up protection you could have had. Match the policy to the chain.
- Trusting forwarded headers blindly. Enabling
forward-headers-strategyon an app that is directly reachable from the internet lets clients fake their scheme and address. - Treating headers as authorization. Headers reduce browser-side risk. They do not replace authentication or role checks.
Exercise
Your API runs behind a load balancer that terminates TLS. Responses show X-Content-Type-Options and X-Frame-Options but no Strict-Transport-Security. Why, and what do you change?
Show answer
Spring Security writes HSTS only when the request is secure. The load balancer forwards plain HTTP, so the application never sees an HTTPS request. Set server.forward-headers-strategy=framework (and make sure the trusted proxy sends X-Forwarded-Proto: https), so the request reports the HTTPS scheme and the header is written. Then confirm with a test that uses .secure(true) and by checking a real response.
Exercise
Why does the actuatorChain bean in this chapter need @Order(1) and a securityMatcher, while the API chain does not need a securityMatcher?
Show answer
With several SecurityFilterChain beans, Spring Security picks the first chain whose matcher accepts the request, in order. The actuator chain must come first and match only actuator paths. The API chain comes last with no matcher, so it catches every request the earlier chains did not take. Without the order and matcher, the catch-all chain could handle actuator requests and apply the wrong rules.