Sub topic 14
Security headers and hardening checklist
This chapter assumes you have read the earlier chapters on the filter chain, stateless sessions, CSRF, CORS and 401/403 handling. It pulls those pieces into a short checklist and shows the response headers Spring Security adds for you.
What Spring Security adds by default
Spring Security's HeaderWriterFilter writes security headers on every response. You get them without configuration.
| Header | Default value | What it does |
|---|---|---|
| `X-Content-Type-Options` | `nosniff` | Stops browsers from guessing a content type. |
| `Cache-Control` | `no-cache, no-store, max-age=0, must-revalidate` | Keeps protected responses out of shared and browser caches. |
| `X-Frame-Options` | `DENY` | Blocks the page from being shown in a frame. |
| `Strict-Transport-Security` | `max-age=31536000 ; includeSubDomains` | Tells browsers to use HTTPS only. Sent only on HTTPS requests. |
For a JSON API these defaults are mostly what you want. Keep them unless you have a specific reason to change one.
Adding headers for an API
A JSON API is not rendered as a page, so the most useful extra header is a restrictive Content-Security-Policy. It limits what a browser may load if a response is ever interpreted as HTML. You can also trim the referrer information the API leaks.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableWebSecurity
public class HardenedSecurityConfig {
@Bean
SecurityFilterChain hardenedApi(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'"))
.referrerPolicy(ref -> ref
.policy(ReferrerPolicy.NO_REFERRER)))
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.httpBasic(basic -> {});
return http.build();
}
}The policy default-src 'none' blocks every resource type. frame-ancestors 'none' forbids framing, which backs up X-Frame-Options.
Enforcing HTTPS
HSTS only helps after a browser has made one HTTPS request. Most deployments terminate TLS at a load balancer, so the application sees plain HTTP. In that case set server.forward-headers-strategy=framework in application.properties, so Spring reads X-Forwarded-Proto and knows the original request was secure. Redirecting HTTP to HTTPS is usually the proxy's job.
Hardening checklist
Work through this list before release.
- Hash passwords with a
PasswordEncoder. Never store or log plain text. - Use
anyRequest().authenticated()as the last rule, so new endpoints are closed by default. - Disable CSRF only for stateless APIs that do not rely on cookies for authentication.
- Allow named CORS origins. Do not combine
*with credentials. - Prefer short-lived JWTs and validate the issuer.
- Add method security for rules that depend on the data, not only the path.
- Return 401 and 403 without stack traces or internal messages.
- Keep secrets such as signing keys and passwords in environment variables or a vault, not in source control.
- Expose only the Actuator endpoints you need and put them behind authentication.
- Test each rule with
spring-security-test, including the denied cases. - Keep Spring Boot and Spring Security up to date. Security fixes ship in patch releases.
Exercise
Your API runs behind a load balancer that terminates TLS, and the response never includes Strict-Transport-Security. What is the likely cause, and what is the fix?
Show answer
Spring Security sends HSTS only on requests it sees as secure. The load balancer forwards plain HTTP, so the app treats the request as insecure. Set server.forward-headers-strategy=framework so Spring honors X-Forwarded-Proto, and make sure the load balancer sends that header.
Exercise
A teammate wants to remove X-Frame-Options and writes http.headers(h -> h.disable()). Why is this a mistake, and what is the targeted alternative?
Show answer
It disables every default security header, including nosniff, cache control and HSTS. To change only framing, use http.headers(h -> h.frameOptions(f -> f.sameOrigin())), or f.disable() if the header must be removed.