Skip to content
Download

CSRF Protection

Cross-Site Request Forgery (CSRF) is an attack in which a malicious site causes a user’s browser to send an unwanted request to another application where the user is authenticated.

Mach provides CSRF protection using the double-submit cookie pattern.

Enable CSRF protection when configuring the application:

int main() {
mach::AppBuilder builder;
builder.addCsrf();
}

Once enabled, Mach manages CSRF tokens and validates protected requests automatically.

Mach uses a CSRF token that is submitted in two places: a cookie and a request header.

The flow is:

  1. Mach generates a CSRF token and sends it to the client in a cookie.
  2. The client reads the token from the cookie.
  3. For protected requests, the client sends the same token in the CSRF request header.
  4. Mach compares the token in the header with the token in the cookie.
  5. If the tokens match, the request continues. Otherwise, the request is rejected with a 403 Forbidden response.

Because another site cannot read the CSRF cookie and reproduce its value in the request header, this prevents forged cross-site requests from passing CSRF validation.

When making a protected request from a browser, read the CSRF token from the cookie and include it in the CSRF header.

For example:

const token = document.cookie
.split("; ")
.find((cookie) => cookie.startsWith("csrf-token="))
?.split("=")[1];
await fetch("/api/profile", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Mach-CSRF": token,
},
credentials: "include",
body: JSON.stringify({
displayName: "Alex",
}),
});

The cookie and header names must match those configured by the application.

You can customize the cookie and request header used for the CSRF token:

builder.addCsrf([](mach::CsrfBuilder& csrf) {
csrf.cookieName("csrf-token")
.headerName("X-Mach-CSRF");
});

The client must use the configured names when submitting the token.

For details about configuring the CSRF cookie and header names, see CsrfBuilder.


For details about configuring the CSRF cookie and header names, see CsrfBuilder.