
# CSRF

Cross-site request forgery is a page on another site making the user's browser send a request to your application, with the user's cookies. CSRF protection makes every state-changing request carry a token that such a page cannot know. It is on by default.

## Why

A browser sends cookies with every request to your site, whoever started it. Without a token, a hidden form on `evil.example` can post to `/api/transfer` as the logged-in user. The other page cannot read your pages or your cookies, so it cannot know the token, and its request fails.

## Example

A single-page or Flutter web app reads the token from a cookie and sends it back in a header:

```dart
@Bean()
SecurityFilterChain filterChain(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth.anyRequest().authenticated())
    .formLogin()
    .csrf((c) => c
        // A cookie scripts can read...
        .csrfTokenRepository(const CookieCsrfTokenRepository.withHttpOnlyFalse())
        // ...whose raw value the script sends back, not a masked token.
        .csrfTokenRequestHandler(const CsrfTokenRequestAttributeHandler())
        // A third party posts to this path; it has its own signature check.
        .ignoringRequestMatchers('/webhooks/**'))
    // Have the cookie before the first POST.
    .addFilterAfter(CsrfCookieFilter(), CsrfFilter)
    .build();

// Reading the token writes the XSRF-TOKEN cookie when it is new.
final class CsrfCookieFilter extends OncePerRequestFilter {
  @override
  Future<void> doFilterInternal(
    ServerHttpRequest request,
    ServerHttpResponse response,
    WebFilterChain chain,
  ) {
    csrfTokenOf(request);
    return chain.doFilter(request, response);
  }
}
```

```javascript
// The browser side: send the cookie's value back in the header.
fetch('/api/books', {
  method: 'POST',
  credentials: 'include',
  headers: {'X-XSRF-TOKEN': readCookie('XSRF-TOKEN'), 'Content-Type': 'application/json'},
  body: JSON.stringify(book),
});
```

## What is checked

- Every method except `GET`, `HEAD`, `TRACE` and `OPTIONS` needs the token, in the header (`X-XSRF-TOKEN` with the default cookie repository) or the form field `_csrf`.
- No token stored for the client yet (a first request): `403`, and a new token is created for the next try.
- A token missing from the request, or not equal to the stored one (compared in constant time): `403`.
- The `403` comes also for anonymous users; they are not asked to log in. A login form posted without the token is refused too.

## Where the token is kept

| Repository | Keeps the token in | Use for |
|---|---|---|
| `CookieCsrfTokenRepository()` (default) | the cookie `XSRF-TOKEN`, `HttpOnly`, `SameSite=Lax`, header `X-XSRF-TOKEN` | pages rendered by the server |
| `CookieCsrfTokenRepository.withHttpOnlyFalse()` | the same cookie, readable by scripts | single-page and Flutter web apps |
| `HttpSessionCsrfTokenRepository()` | the session, header `X-CSRF-TOKEN` | Spring's default; makes a session for every visitor |

`CookieCsrfTokenRepository` takes `cookieName`, `headerName`, `parameterName`, `cookieHttpOnly`, `cookiePath`, `cookieDomain` and `sameSite`. The token is created only when something reads it or a check needs it.

## Pages rendered by the server

Put the token in each form as a hidden field. `csrfTokenOf(request)` gives it, and creates it when the client has none:

```dart
@GetMapping('/form')
String form(ServerHttpRequest request) {
  final csrf = csrfTokenOf(request)!;
  return '<form method="post" action="/books">'
      '<input type="hidden" name="${csrf.parameterName}" value="${csrf.token}">'
      '<button>Add</button></form>';
}
```

By default each page gets the token masked with fresh random bytes (`XorCsrfTokenRequestAttributeHandler`), so the bytes are never the same twice and cannot be guessed from the size of compressed responses (BREACH).

## Single-page and Flutter web apps

They render no forms: they read the token from the `XSRF-TOKEN` cookie and send it in the `X-XSRF-TOKEN` header. That needs two settings together, as in the example: a cookie scripts can read, and the handler that accepts the raw value (`CsrfTokenRequestAttributeHandler`). With the cookie alone, the default handler expects a masked token, and the raw value is refused with `403`. Add the filter that reads the token on every request, so the cookie exists before the first `POST`.

## Exemptions

| Situation | CSRF |
|---|---|
| `csrf((c) => c.ignoringRequestMatchers('/webhooks/**'))` | Those paths are exempt (up to four patterns per call; call it several times). |
| A request with `Authorization: Bearer`, or `DPoP` with a proof, in a chain with `oauth2ResourceServer()` | Exempt, as in Spring: a browser never adds these headers by itself, and the token logs the request in or it is refused with `401`. The chain's browser session requests keep their check. |
| A token in the `access_token` query parameter | Never exempt: any page can post a form to such a URL. |
| The chain's logout URL and form login URL | Keep their check even with a token header: their filters act on the browser's session before any token is looked at (Spring exempts them). |
| The `oauth2Login()` callback `POST` (`response_mode=form_post`) | Exempt; the `state` bound to the browser protects it. |

A filter of your own placed before the token filters sees a token request before its token is checked: it must not act on the session for it.

## Turning it off

`csrf((c) => c.disable())` is for chains whose clients send their credentials only in headers (Basic, bearer tokens), never in cookies. A browser does not send those headers by itself, so another site cannot forge such a request. A browser session without CSRF protection can be used by any page the user visits. Turning it off also lets `GET /logout` log out.

## In tests

`MockMvc` requests that change state need the token: add `..with_(csrf())` (see [Testing](testing.md)).

## In Spring (Java)

```java
http.csrf(c -> c
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()));
```

The classes are Spring's. Differences: the default repository is the cookie, not the session, so visitors without a login make no session; only a token in a header exempts a request (Spring exempts what its `BearerTokenResolver` finds, which can include a form field); the logout and login URLs keep their check with a token header. `csrf.spa()` is not here yet.

## See also

- [Sessions](sessions.md)
- [JWT resource servers](jwt.md)
- [Single sign-on](oauth2-login.md)
