Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 66 ยท Security

CSRF, CORS and Secure Defaults

Harden a Spring Boot app: when CSRF protection matters, SameSite cookies, CORS rules, security headers, rate limiting, secrets and risky default settings.

Authentication answers "who are you?", but a secure application also has to answer "is this request really what the user intended?" and "which websites may talk to my API from a browser?". Those are the jobs of CSRF protection and CORS. Add to that a handful of response headers, a few risky configuration settings, and careful handling of secrets, and you have the checklist that separates a demo from something you can put on the internet.

Spring Security gives you good defaults for most of this, but defaults only help if you understand them. Turning off CSRF "because the POST returns 403" is one of the most common ways to open a hole. This lesson explains what each protection does, when you may switch it off, and how to configure it in a Boot application. It builds on Spring Security Fundamentals and JWT and OAuth 2 Resource Server; for the Java-level background see Web Security Basics.

Spring Security cannot run on this site, so real configuration is shown in read-only blocks. The TryIts are small stand-ins that implement the same checks in plain Java, so you can see exactly what is decided and why.

Four layers of web hardening

CSRF Stop other sites from riding your cookie.
CORS Decide which origins browsers may call from.
Headers Tell the browser how to treat your pages.
Secrets Keep keys and passwords out of the repo.
1 / 2

What CSRF is, and why cookies are the problem

Cross-Site Request Forgery abuses a browser habit: when a page on evil.example makes a request to bank.example, the browser attaches the user's bank.example cookies automatically. If the bank accepts "POST /transfer" based on the session cookie alone, the attacker's page can trigger a transfer without ever seeing the cookie or the response.

sequenceDiagram
    participant U as Browser (logged in)
    participant E as evil.example
    participant B as bank.example
    U->>E: Visit a page
    E-->>U: Hidden form that posts to bank.example
    U->>B: POST /transfer (cookie attached automatically)
    B-->>U: "OK" if no CSRF check exists

The attacker never sees the cookie. The browser sends it for them.

The defence is a secret the attacker's page cannot know. The server creates a random CSRF token for the session, the legitimate page includes it in every state-changing request (as a hidden form field or a header), and the server compares it. A forged request carries the cookie but not the token, so it is rejected.

Java A CSRF token check

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.

What is real: state-changing methods need a matching token and safe methods do not. What is the stand-in: Spring Security's CsrfFilter also masks the token on every response (protection against the BREACH compression attack), supports a token stored in a cookie or the session, and ignores the check for configured paths.

Do I need it at all?

CSRF only works because the browser adds credentials automatically. That gives a simple rule:

  • Session cookie authentication (server-side pages, a SPA that logs in with a cookie): keep CSRF protection on. It is the default.
  • Bearer tokens in an Authorization header (a stateless API authenticated with JWTs): the browser never attaches that header by itself, so there is nothing to forge. Disabling CSRF is reasonable here.
Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())                       // only because auth is a bearer token
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
    return http.build();
}

Read that code with care. The disable() call is justified by the two lines below it. If you later add a cookie login to the same application, the justification is gone and so must the disable(). For a single-page app that keeps its session in a cookie, expose the token to JavaScript with CookieCsrfTokenRepository.withHttpOnlyFalse() (the script reads it and sends it back as the X-XSRF-TOKEN header) and follow the Spring Security reference for the SPA token handler.

SameSite cookies: a second layer

The SameSite cookie attribute tells the browser when to attach a cookie to a cross-site request. Lax (the default in modern browsers) holds it back for cross-site POSTs, which kills the classic attack, and Strict holds it back for nearly all cross-site requests. In Boot you set it for the session cookie:

YAML
server:
  servlet:
    session:
      cookie:
        http-only: true
        secure: true
        same-site: lax

Treat SameSite as defence in depth, not a replacement for the token: it depends on browser behaviour, and sites on the same registrable domain (app.example.com and blog.example.com) count as "same site".

CORS: a browser rule, not a security feature of your API

Browsers apply the same-origin policy: JavaScript on https://app.example may not read responses from https://api.example unless the API says so. CORS (Cross-Origin Resource Sharing) is how the API says so, using headers such as Access-Control-Allow-Origin. For requests with custom headers or methods like PUT, the browser first sends a preflight OPTIONS request to ask permission.

Three facts clear up most confusion:

  1. CORS is enforced by browsers only. curl, a mobile app or another server ignore it, so it never replaces authentication.
  2. A CORS error means the response was withheld from the script, not that the request failed. A POST may still have run on the server.
  3. The wildcard * cannot be combined with credentials. Spring rejects allowedOrigins("*") together with allowCredentials(true).

In a Boot application that uses Spring Security, define a CorsConfigurationSource and switch CORS handling on, so that preflight requests are answered before the authentication filter rejects them:

Java
@Bean
CorsConfigurationSource corsConfigurationSource() {
    var config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://app.example.com"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    config.setAllowCredentials(true);
    config.setMaxAge(Duration.ofHours(1));

    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
    http.cors(Customizer.withDefaults());
    // ... the rest of your rules
    return http.build();
}

Without Spring Security, @CrossOrigin on a controller or WebMvcConfigurer.addCorsMappings does the same job. List exact origins. Echoing back whatever Origin header arrives, together with credentials, is equivalent to turning the protection off.

Security headers

Headers instruct the browser how to treat what you send. Spring Security adds several by default: X-Content-Type-Options: nosniff (do not guess content types), X-Frame-Options: DENY (do not allow framing, which prevents clickjacking), cache-control headers that keep authenticated responses out of caches, and Strict-Transport-Security on HTTPS responses. Others you must add yourself, notably Content-Security-Policy, which limits where scripts and styles may load from and is your best defence against cross-site scripting.

Java
http.headers(h -> h
    .contentSecurityPolicy(csp -> csp.policyDirectives(
        "default-src 'self'; script-src 'self'; frame-ancestors 'none'"))
    .referrerPolicy(r -> r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)));

HSTS only makes sense when the whole site is served over HTTPS; behind a reverse proxy, make sure the proxy forwards the original scheme (server.forward-headers-strategy=framework or native) so Boot knows the request was secure.

The TryIt below audits a response's headers and answers CORS questions the way a server would. Run it and then change the allowed origins to see how the decisions change.

Java Auditing headers and CORS decisions

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.

What is real: the header names and what each missing one allows. What is the stand-in: the exact header set Spring Security sends depends on its version and on whether the request used HTTPS, and a real CORS filter also validates the method and headers of a preflight request.

Rate limiting and brute force

Login endpoints, password resets and expensive searches need a limit on how often one client can call them. Spring Boot has no built-in rate limiter, so you choose: a reverse proxy or API gateway (usually the best place, since it protects every service), a library such as Bucket4j in a filter (see Filters, Interceptors and Argument Resolvers), or Resilience4j's rate limiter. The most common algorithm is a token bucket: the bucket holds up to N tokens, each request takes one, and tokens refill at a steady rate. A burst is allowed until the bucket is empty, then requests are rejected with 429 Too Many Requests.

Java A token bucket with a fake clock

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.

In production the bucket must be keyed (per IP address, user or API key) and shared if you run several instances, which usually means Redis or the gateway. Behind a proxy, read the client address from X-Forwarded-For only if you trust the proxy; otherwise anyone can spoof it.

Secrets and risky settings

Secrets (database passwords, API keys, JWT signing keys) never belong in the repository or in a Docker image. Read them from environment variables or a secrets store: Boot maps SPRING_DATASOURCE_PASSWORD to spring.datasource.password, supports mounted secret files with spring.config.import=configtree:/run/secrets/, and integrates with Vault and cloud secret managers. Commit a .env.example with fake values, never the real file, and rotate any secret that was ever pushed to git: deleting the commit is not enough. See Profiles and Environment-Specific Config for how config sources layer.

A short review list of Boot-specific mistakes that show up again and again:

Misconfiguration Why it hurts Fix
management.endpoints.web.exposure.include=* on a public port env, heapdump, beans and loggers can leak data or let attackers change log levels Expose only health (and what you need), secure the rest, or use a separate management port; see Actuator
spring.jpa.hibernate.ddl-auto=update or create-drop in production Schema changes happen on startup without review; create-drop can erase data Use validate or none and migrations (Flyway)
spring.h2.console.enabled=true outside development A database console on your server Keep it off, or profile-limit it
server.error.include-stacktrace=always or include-message=always Stack traces and internals reach clients Keep the defaults (never) and return clean problem responses (Error Handling)
logging.level.org.springframework.security=TRACE in production Tokens and request details in log files Use DEBUG only temporarily
Dev-only users or password defaults left in application.yml Predictable credentials Load users from a real store; no defaults
Binding entities directly to request bodies Mass assignment: clients set fields like role or admin Use DTOs and copy only allowed fields

Finally, keep dependencies patched. Boot's BOM means upgrading one version number updates hundreds of libraries, so staying current is cheap, and a scheduled dependency scan in your CI will tell you when a library has a known vulnerability.

Never write your own cryptography or token scheme to avoid learning Spring Security. Use BCryptPasswordEncoder or DelegatingPasswordEncoder for passwords, standard JWT libraries for tokens, and HTTPS everywhere. Homemade security fails quietly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your API authenticates only with a bearer token in the Authorization header and keeps no sessions. Why is it reasonable to disable CSRF protection?

    CSRF relies on the browser attaching credentials automatically, as it does with cookies. A header that your own JavaScript must set explicitly is not attached by another site's page.
  2. 2. A browser console shows a CORS error for a POST request. What is true?

    CORS is a browser rule about reading responses. The request can still run on the server, which is why CORS is no substitute for authentication or CSRF protection.
  3. 3. Which configuration is rejected by Spring because it is unsafe?

    With credentials, the response must name an exact origin (or use allowedOriginPatterns). A wildcard would let any site make credentialed calls.
  4. 4. What does a token bucket rate limiter allow that a fixed "one request per second" rule does not?

    The bucket fills up while the client is quiet, so a burst is accepted until it is empty, then requests are limited to the refill rate.
  5. 5. Which setting is the riskiest in a production Boot application?

    Wildcard exposure publishes endpoints such as env, heapdump and loggers. The other three settings are safe or recommended.

Summary

  • Keep CSRF protection on for cookie-based authentication; disable it only for stateless apps that authenticate with an explicit header such as a bearer token.
  • Set session cookies HttpOnly, Secure and SameSite=Lax or stricter, as a second layer behind the CSRF token.
  • CORS is a browser rule: list exact origins, never combine * with credentials, and never treat it as authentication.
  • Spring Security adds several headers by default; add a Content-Security-Policy and review the rest.
  • Rate limit login and expensive endpoints, preferably at a gateway, with a keyed and shared token bucket.
  • Load secrets from the environment or a secrets store, and review ddl-auto, actuator exposure, the H2 console and error detail before going live.

Next: Testing Spring Boot Applications.