Full Stack • Java • System Design • Cloud • AI Engineering

Security Headers in Spring Boot

Learn security headers in Spring Boot and Spring Security, including CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and browser hardening.

What You Will Learn

  • Why HTTP security headers matter.
  • What common headers do.
  • How Spring Security configures headers.
  • How CSP reduces script injection risk.
  • Production hardening tips.

Introduction

Security headers tell browsers how to handle your application safely.

They help reduce:

  • Clickjacking.
  • MIME sniffing.
  • Mixed content.
  • Script injection impact.
  • Information leakage.

Common Headers

Header Purpose
Content-Security-Policy Controls allowed scripts, styles, images, and connections
Strict-Transport-Security Forces HTTPS
X-Frame-Options Reduces clickjacking
X-Content-Type-Options Prevents MIME sniffing
Referrer-Policy Controls referrer leakage

Spring Security Example

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .headers(headers -> headers
            .contentSecurityPolicy(csp -> csp
                .policyDirectives("default-src 'self'; frame-ancestors 'none'")
            )
            .httpStrictTransportSecurity(hsts -> hsts
                .includeSubDomains(true)
                .preload(true)
                .maxAgeInSeconds(31536000)
            )
        );

    return http.build();
}

Header Flow

flowchart LR
    A["Spring Security"] --> B["Response headers"]
    B --> C["Browser"]
    C --> D["Enforce browser policy"]

Production Tips

  • Test CSP in report-only mode first.
  • Use HTTPS everywhere before HSTS preload.
  • Avoid allowing broad script sources.
  • Review headers after CDN or gateway changes.

Summary

Security headers harden browser behavior. They are a low-cost, high-value layer in Java web application security.

Learning Path Navigation

Loading likes...

Comments

Share a question, correction, or practical insight about this article.

Loading approved comments...