==== CsrfHandler

The javadoc:handler.CsrfHandler[text="Cross-Site Request Forgery (CSRF) Handler"] protects your application against unauthorized commands performed on behalf of an authenticated user.

Jooby generates a unique CSRF token for each active user session. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define an HTML form that performs a state-changing operation (like `POST`), you must include the CSRF token.

.HTML Form with CSRF
[source, html]
----
<form method="POST" action="/update-profile">
    <input name="csrf" value="{{csrf}}" type="hidden" />
    <button type="submit">Update</button>
</form>
----

In the example above, `{{csrf}}` is a request attribute created by the handler. When the form is submitted, the javadoc:handler.CsrfHandler[] automatically verifies that the token in the request matches the token stored in the user's session.

===== Usage

CSRF protection requires an active **Session Store** to be configured first.

.CSRF Usage
[source, java, role = "primary"]
----
import io.jooby.handler.CsrfHandler;

{
  // 1. Session store is required
  setSessionStore(SessionStore.memory());

  // 2. Install CSRF handler
  use(new CsrfHandler());
  
  get("/form", ctx -> {
    // Token is available as a request attribute
    return new ModelAndView("form.hbs", Map.of("csrf", ctx.getAttribute("csrf")));
  });
}
----

.Kotlin
[source, kotlin, role = "secondary"]
----
import io.jooby.handler.CsrfHandler

{
  // 1. Session store is required
  sessionStore = SessionStore.memory()

  // 2. Install CSRF handler
  use(CsrfHandler())
  
  get("/form") { ctx ->
    // Token is available as a request attribute
    ModelAndView("form.hbs", mapOf("csrf" to ctx.getAttribute("csrf")))
  }
}
----

===== Token Delivery

By default, the handler looks for a token named `csrf` in the following order:

1.  **HTTP Header:** `X-CSRF-Token` or `csrf`
2.  **Cookie:** `csrf`
3.  **Form Parameter:** `csrf`

===== Customization

You can customize the behavior of the handler using the following methods:

* javadoc:handler.CsrfHandler[setTokenGenerator, java.util.function.Function]: Customize how tokens are generated (defaults to a random UUID).
* javadoc:handler.CsrfHandler[setRequestFilter, java.util.function.Predicate]: Define which requests should be validated. By default, it validates `POST`, `PUT`, `PATCH`, and `DELETE` requests.

[TIP]
====
If you are building a Single Page Application (SPA), you can configure the handler to read the token from a custom header and have your frontend (e.g., React or Vue) send it back on every request.
====
