Skip to lesson

CSRF and when it matters

Meena is signed in to the ShopLite admin console. She opens another website in a new tab, and a product is deactivated without a click from her. How can a page she never trusted act as her?

The CSRF attack step by step

Cross-site request forgery (CSRF) is an attack that makes a signed-in user's browser send a request the user never meant to send. It works because a browser adds a site's cookies to every request to that site.

Another website cannot read Meena's session cookie, but it can make her browser send it. The steps below show the attack.

Text
Step 1  Meena (an admin) signs in to the ShopLite admin console.        Her browser now holds its JSESSIONID cookie.Step 2  In another tab she opens a page on some other site,        for example a "free fest coupons" page.Step 3  That page contains a hidden form that its script submits at once:        POST https://admin.shoplite.example/admin/products/8/deactivateStep 4  The browser attaches Meena's JSESSIONID to that POST by itself.Step 5  Without CSRF protection the server sees a valid admin session        and deactivates product 8. Meena saw nothing happen.
  • The other site never sees the reply: browsers keep pages from reading responses of other sites (the same-origin policy). It does not need the reply, only the side effect.
  • Targets are actions that change data: deactivate a product, change an email, place an order, transfer money.
  • Login with HTTPS, HttpOnly and a strong password does not help: the request really comes from the victim's browser.

How Spring's CSRF token works

A CSRF token is a random value that the server keeps in the user's session and puts into its own pages. Spring's CsrfFilter accepts POST, PUT, PATCH and DELETE only when the request carries the same value, otherwise it answers 403 Forbidden.

The first example posts to the admin console without the token and then with it; the second proves the same in a test.

Example 1 · A POST without the token, then with it

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/admin/CsrfController.javapackage com.shoplite.lab.admin;
import org.springframework.security.web.csrf.CsrfToken;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerclass CsrfController {
    record CsrfView(String headerName, String parameterName, String token) {    }
    /** Spring passes the current CsrfToken as a parameter, like Authentication. */    @GetMapping("/admin/csrf")    CsrfView csrf(CsrfToken token) {        return new CsrfView(token.getHeaderName(), token.getParameterName(), token.getToken());    }}
Sample output
(jar.txt holds the admin's session; OLD_TOKEN is the _csrf value from the login page, before signing in)

$ curl -i -b jar.txt -X POST http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:20:26 GMT

{"timestamp":"2026-10-16T07:20:26.438Z","status":403,"error":"Forbidden","path":"/admin/products/8/deactivate"}

$ curl -b jar.txt http://localhost:8080/admin/csrf
{"headerName":"X-CSRF-TOKEN","parameterName":"_csrf","token":"gufRUNdpnksOX3v63q5aC26TapRLo5H_oedzAkMQMAdROzDD5oTlY7YMpi0jO0_IvINubVz3R6x-xafSxNVFM3cgBjc1D1Tz"}

$ curl -b jar.txt http://localhost:8080/admin/csrf
{"headerName":"X-CSRF-TOKEN","parameterName":"_csrf","token":"nlsAjFOhw5puA5k81bV3ZsB3_TrmjuhyBcr-wH3HgOVENI06-jg0vzLE-_xDZ60Ot5hDAPIT0ALT6N5fYPjI8Un3ttUgAOkK"}

$ TOKEN=$(curl -s -b jar.txt http://localhost:8080/admin/csrf | sed 's/.*"token":"\([^"]*\)".*/\1/')
$ curl -i -b jar.txt -X POST -H "X-CSRF-TOKEN: $TOKEN" http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 62
Date: Fri, 16 Oct 2026 07:20:28 GMT

{"id":8,"isActive":false,"changedBy":"admin@shoplite.example"}

$ curl -b jar.txt -d "_csrf=$TOKEN" http://localhost:8080/admin/products/8/deactivate
{"id":8,"isActive":false,"changedBy":"admin@shoplite.example"}

$ curl -b jar.txt -X POST -H "X-CSRF-TOKEN: $OLD_TOKEN" http://localhost:8080/admin/products/8/deactivate
{"timestamp":"2026-10-16T07:20:29.509Z","status":403,"error":"Forbidden","path":"/admin/products/8/deactivate"}

What this code does

  • The first POST is exactly what a forged form produces: a valid admin cookie and no token. Spring answers 403 and the controller never runs.
  • The token is masked, so it looks different on every call; either copy works, in the X-CSRF-TOKEN header or as the _csrf form field.
  • The token from the login page, taken before signing in, is rejected: Spring made a new one at login.

Example 2 · src/test/java/com/shoplite/lab/admin/CsrfRulesTest.java

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
package com.shoplite.lab.admin;
import static org.assertj.core.api.Assertions.assertThat;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.HttpStatus;import org.springframework.security.test.context.support.WithMockUser;import org.springframework.test.web.servlet.assertj.MockMvcTester;
import com.shoplite.lab.security.SecurityConfig;
@WebMvcTest(AdminController.class)@Import(SecurityConfig.class)class CsrfRulesTest {
    @Autowired    private MockMvcTester mvc;
    @Test    @WithMockUser(username = "admin@shoplite.example")    void postWithoutTokenIsForbidden() {        assertThat(mvc.post().uri("/admin/products/8/deactivate"))                .hasStatus(HttpStatus.FORBIDDEN);    }
    @Test    @WithMockUser(username = "admin@shoplite.example")    void postWithTokenWorks() {        assertThat(mvc.post().uri("/admin/products/8/deactivate").with(csrf()))                .hasStatusOk()                .bodyJson().extractingPath("$.changedBy").isEqualTo("admin@shoplite.example");    }
    @Test    @WithMockUser(username = "admin@shoplite.example")    void postWithWrongTokenIsForbidden() {        assertThat(mvc.post().uri("/admin/products/8/deactivate").with(csrf().useInvalidToken()))                .hasStatus(HttpStatus.FORBIDDEN);    }
    @Test    void guestIsSentToTheLoginPage() {        assertThat(mvc.get().uri("/admin"))                .hasStatus(HttpStatus.FOUND)                .hasRedirectedUrl("/login");    }}
Sample output
$ mvn test -Dtest=CsrfRulesTest
...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.lab.admin.CsrfRulesTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.61 s -- in com.shoplite.lab.admin.CsrfRulesTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

What this code does

  • @WithMockUser puts a signed-in user into the test, so each test checks only the CSRF rule. with(csrf()) adds a valid token; csrf().useInvalidToken() adds a wrong one.
  • The tests need the spring-boot-starter-security-test dependency, the same one the earlier security tests used.

The attacking site cannot get the token: it cannot read the admin console's pages (same-origin policy), and the value is random, so guessing is useless. Its forged form carries the cookie but no token, so it fails. GET, HEAD, OPTIONS and TRACE are not checked, because they must not change anything.

Where the token shows up:

  • Forms in Thymeleaf with th:action get the hidden _csrf field automatically; Spring's own login and logout pages include it too.
  • A controller can take CsrfToken as a parameter to hand the token to JavaScript, and with(csrf()) from spring-security-test adds a valid one in tests.
  • Spring sends the token masked: a random mask is mixed in on every render, so the text differs each time while the real secret stays the same (a defence against an HTTPS attack called BREACH).
  • Spring makes a new token at login, so a token copied before login is worthless afterwards.

Fix the error

Fix the 403 on a POST

Each call is rejected with 403. Choose the line that makes it carry the CSRF token.

Round 1 of 2

This admin page posts a form and gets 403. Fix line 2.

<!-- admin/product.html (Thymeleaf) -->
<form method="post" action="/admin/products/8/deactivate">
<button type="submit">Deactivate</button>
</form>

Error

HTTP/1.1 403
{"status":403,"error":"Forbidden","path":"/admin/products/8/deactivate"}

SameSite cookies as an extra defence

SameSite is a cookie flag that tells the browser not to attach the cookie to requests that other sites start. With SameSite=Lax, a form posted from another site arrives without the session cookie.

The example breaks a rule on purpose: a GET request that changes data. It shows what neither CSRF protection nor SameSite covers.

Example 3 · A mistake on purpose: a GET that changes data

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
// src/main/java/com/shoplite/lab/admin/UnsafeGetController.javapackage com.shoplite.lab.admin;
import org.springframework.security.core.Authentication;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;
/** A MISTAKE ON PURPOSE: a GET request that changes data. CSRF protection never checks GET. */@RestControllerclass UnsafeGetController {
    record ProductStatus(int id, boolean isActive, String changedBy) {    }
    @GetMapping("/admin/products/{id}/deactivate")    ProductStatus deactivateWithGet(@PathVariable int id, Authentication authentication) {        return new ProductStatus(id, false, authentication.getName());    }}
Sample output
$ curl -b jar.txt http://localhost:8080/admin/products/8/deactivate
{"id":8,"isActive":false,"changedBy":"admin@shoplite.example"}

What this code does

  • No token was sent, yet the "deactivate" ran: CsrfFilter does not check GET, by design.
  • A plain link on another page would do the same when clicked, because SameSite=Lax still sends the cookie on a link click. The fix is to make the action a POST and delete this endpoint.

With SameSite=Lax, step 4 of the attack fails even without a token, and Strict also leaves the cookie off when the user clicks a link from another site. SameSite is a second layer, not a replacement for the token: Lax still sends the cookie on a link click (a top-level GET), older browsers ignore the flag, and pages on your own sub-domains count as the "same site". Chrome treats a cookie with no SameSite as Lax, but not every browser does, so set it yourself.

Both defences assume one rule: GET never changes data. CSRF protection never checks GET, and Lax lets the cookie through on a link click, so a GET that deactivates a product can be triggered from any page.

When disabling CSRF is safe: stateless APIs with the Authorization header

ShopLite's API turns CSRF protection off. The example shows what that changes for a client that signs in with Basic.

Example 4 · Basic with CSRF on and off

Runs in: the basic-lab practice project (Spring Boot 4.1)

Java
// basic-lab SecurityConfig: the csrf line decides.httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable())          // remove this line and POSTs need a token.sessionManagement(session -> session    .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
Sample output
1) basic-lab with the csrf(...) line removed (CSRF protection ON):

$ curl -i -X POST -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me/orders
HTTP/1.1 403
Set-Cookie: JSESSIONID=1FA1C703A171C1E40995D703A72615E3; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:22:03 GMT

{"timestamp":"2026-10-16T07:22:03.316Z","status":403,"error":"Forbidden","path":"/api/v1/me/orders"}

$ curl -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

2) basic-lab as written, with .csrf(csrf -> csrf.disable()):

$ curl -i -X POST -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me/orders
HTTP/1.1 201
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 61
Date: Fri, 16 Oct 2026 07:23:34 GMT

{"id":15,"customer":"asha.rao@example.com","status":"PLACED"}

What this code does

  • With protection on, a POST with the right password still gets 403: Spring wants a CSRF token on every POST. A GET with the same password works, because GET is not checked.
  • The 403 even sets a JSESSIONID: the default token store keeps the token in a session, so STATELESS alone does not stop session creation.
  • With the line back, the POST is placed (201). For an API whose callers add the header themselves, this is the correct setting.

Disabling CSRF protection is safe only when the browser never adds the credentials by itself. An API that signs requests with an Authorization header (a Basic secret or a bearer token that the app's own code adds) is safe: a forged form from another site cannot add that header, so it arrives unauthenticated. That is why the ShopLite API config says csrf(csrf -> csrf.disable()) next to STATELESS; with protection left on, even a correct curl -u POST gets 403, because Spring does not know that this client is safe.

One trap: a browser that has shown the Basic pop-up remembers those credentials and sends them automatically, just like a cookie. Basic used from a browser is therefore open to CSRF too. The safe case is a program, or a page whose own script adds the header.

Never copy csrf.disable() from an API tutorial into an app that signs in with a session cookie. The practice lesson shows a forged POST succeeding in exactly that case.

The rule: if the browser sends credentials automatically, you need CSRF protection

csrf.spa() is the Spring Security 7 setting for browser apps that sign in with a session cookie: it puts the token in a readable XSRF-TOKEN cookie that the app's script copies into an X-XSRF-TOKEN header.

Some single-page apps (React or Angular) still sign in with a session cookie. The example shows the token flow for them.

Example 5 · csrf.spa(): the token in a readable cookie

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
// session-lab SecurityConfig for a single-page app that keeps the session cookie.formLogin(Customizer.withDefaults()).logout(Customizer.withDefaults()).csrf(csrf -> csrf.spa());     // XSRF-TOKEN cookie + X-XSRF-TOKEN header
Sample output
(session-lab with .csrf(csrf -> csrf.spa()); TOKEN taken from the login page as before)

$ curl -i -b jar.txt -c jar.txt -d "username=admin@shoplite.example&password=Admin%23Lab2026&_csrf=$TOKEN" http://localhost:8080/login
HTTP/1.1 302
Set-Cookie: XSRF-TOKEN=; Expires=Thu, 01 Jan 1970 00:00:10 GMT; Path=/
Set-Cookie: XSRF-TOKEN=709ae6a6-dfe9-4a02-8de1-d11be5620352; Path=/
Set-Cookie: JSESSIONID=D993DEBB6C6348CB615C873DF44BD4E5; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/
Content-Length: 0
Date: Fri, 16 Oct 2026 07:27:34 GMT

$ curl -i -b jar.txt -c jar.txt -X POST http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:27:36 GMT

{"timestamp":"2026-10-16T07:27:36.380Z","status":403,"error":"Forbidden","path":"/admin/products/8/deactivate"}

$ curl -i -b jar.txt -c jar.txt -X POST -H 'X-XSRF-TOKEN: 709ae6a6-dfe9-4a02-8de1-d11be5620352' http://localhost:8080/admin/products/8/deactivate
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 62
Date: Fri, 16 Oct 2026 07:27:37 GMT

{"id":8,"isActive":false,"changedBy":"admin@shoplite.example"}

What this code does

  • After login Spring sets XSRF-TOKEN, a cookie without HttpOnly, so the app's own JavaScript can read it. The session cookie stays HttpOnly.
  • A POST with only the cookies fails; a POST that copies the cookie value into the X-XSRF-TOKEN header works. Another site can make the browser send the cookies but cannot read them to build the header.

The rule fits in one line: if the browser attaches the credentials by itself (cookies, or remembered Basic credentials), keep CSRF protection on; if your own code adds them to each request (an Authorization header), you may switch it off. Another site cannot copy the XSRF-TOKEN cookie into a header, because it cannot read your cookies.

What to choose:

  • Server-rendered pages with a session cookie (the admin console): CSRF on, the default.
  • Single-page app with a session cookie: CSRF on, with csrf.spa().
  • Mobile app or other program with a bearer token in the header: CSRF off, with STATELESS.
  • Token kept in a cookie (some apps do this): the browser sends it automatically again, so CSRF on.

Next step

Check your understanding

12 quick questions