Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท CSRF, CORS and Headers

Security Headers and Session Protection

Configure Spring Security response headers (HSTS, CSP, frame options, nosniff), cookie flags and session fixation protection, with runnable Java stand-ins.

Not every attack is stopped by checking the user. Some are stopped by telling the browser how to treat your pages: do not render me in an iframe, only run scripts from these sources, only talk to me over HTTPS. Spring Security adds a set of such security headers to every response by default, and it protects the session itself against session fixation. This lesson covers both.

The real configuration code is read-only (Spring cannot run on this site); the runnable examples are plain Java stand-ins that generate headers and model the session logic.

Default headers

Spring Security sends these headers out of the box for servlet applications:

Header Value Protects against
X-Content-Type-Options nosniff Browsers guessing a file is a script
Strict-Transport-Security max-age=31536000 ; includeSubDomains (HTTPS only) Downgrade to HTTP, cookie theft on plain HTTP
X-Frame-Options DENY Clickjacking: your page inside an attacker's iframe
Cache-Control no-cache, no-store, max-age=0, must-revalidate Sensitive pages left in browser or proxy caches
X-XSS-Protection 0 Disabled on purpose: the old filter caused bugs

HSTS is only emitted on HTTPS responses. Once a browser has seen it, it refuses plain-HTTP connections to your domain for the given time, so make sure HTTPS works everywhere before you enable long durations.

Customizing headers

Java
http.headers(h -> h
    .contentSecurityPolicy(csp -> csp.policyDirectives(
        "default-src 'self'; script-src 'self'; img-src 'self' data:; frame-ancestors 'none'"))
    .httpStrictTransportSecurity(hsts -> hsts
        .includeSubDomains(true).maxAgeInSeconds(31536000))
    .frameOptions(f -> f.sameOrigin())               // allow our own iframes only
    .referrerPolicy(r -> r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
    .permissionsPolicyHeader(p -> p.policy("camera=(), microphone=(), geolocation=()")));

Content Security Policy

CSP is the strongest defence against cross-site scripting (XSS). It is a whitelist: the page may load scripts, styles, images and frames only from sources you list. Even if an attacker injects <script>, the browser refuses to run it unless the policy allows it.

Key directives:

Directive Controls
default-src Fallback for everything not listed
script-src JavaScript sources (avoid 'unsafe-inline')
style-src CSS sources
img-src Images (often add data:)
connect-src fetch, XHR, WebSocket targets
frame-ancestors Who may embed this page (modern replacement for X-Frame-Options)
object-src 'none' Blocks plugins

For inline scripts you cannot avoid, use a per-response nonce: the policy says script-src 'nonce-R4nd0m', and only <script nonce="R4nd0m"> runs. The nonce must be unpredictable and new for every response.

Java Build a CSP header with a nonce (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Roll out CSP with Content-Security-Policy-Report-Only first: the browser reports what it would block without breaking the site, and you tune the policy from the reports.

The session cookie JSESSIONID should have three flags. In Spring Boot:

YAML
server:
  servlet:
    session:
      cookie:
        http-only: true      # scripts cannot read it
        secure: true         # only sent over HTTPS
        same-site: lax       # not sent on cross-site POSTs
      timeout: 30m

HttpOnly limits the damage of XSS, Secure stops sniffing on plain HTTP, and SameSite backs up CSRF protection.

Session fixation

In a session fixation attack the attacker obtains a valid session id from your site (just by visiting), plants it in the victim's browser (through a link or an injected cookie) and waits for the victim to log in. If the server keeps the same session id through the login, the attacker's copy of the id is now authenticated.

The defence is to issue a new session id at login. Spring Security does this by default (changeSessionId), and you can choose the strategy:

Java
http.sessionManagement(s -> s
    .sessionFixation(fix -> fix.changeSessionId())      // default; alternatives: newSession(), migrateSession()
    .maximumSessions(1));                                // optional: one active login per user
Java Session fixation with and without protection (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Logout should invalidate the session and delete the cookie: logout(l -> l.invalidateHttpSession(true).deleteCookies("JSESSIONID")).
  • HTTPS enforcement: http.requiresChannel(c -> c.anyRequest().requiresSecure()). Behind a proxy, configure server.forward-headers-strategy=framework so Spring knows the original scheme.
  • Concurrent sessions: maximumSessions(1) plus an HttpSessionEventPublisher bean limits parallel logins.

After deploying, test your site's headers with a browser's developer tools or a scanner and fix what is missing. Headers cost nothing and close whole classes of attacks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header prevents your page from being embedded in an attacker's iframe by default in Spring Security?

    X-Frame-Options (or CSP frame-ancestors) controls who may frame the page, defending against clickjacking.
  2. 2. What does a CSP nonce do?

    An injected script cannot know the per-response nonce, so the browser refuses it.
  3. 3. How does Spring Security stop session fixation by default?

    changeSessionId gives a new id after login, so a planted id is worthless.
  4. 4. Why roll out a new CSP in report-only mode first?

    Report-only logs violations without blocking, so you can fix legitimate resources before enforcing.

Summary

  • Spring Security adds protective headers by default: nosniff, HSTS (HTTPS), frame options and no-cache.
  • A Content Security Policy whitelists script and resource sources and is the strongest XSS mitigation; use nonces for inline scripts.
  • Mark session cookies HttpOnly, Secure and SameSite.
  • Session fixation is stopped by changing the session id on login, which is the default.
  • Test headers after each deployment.

Next: Testing secured applications